In my my main activity layout(first layout) I have dynamically set up text views. Now, when these text views are clicked, I want to display another layout(second layout) again having text views(dynamically set). When these text views are clicked I want the text of this text view of this second layout to be set as the text of the text view of the first layout which was clicked.
For eg.
first layout -> [click] [click] ->be the two text views in the layout. Suppose I click the first, then I want to display
[english] [maths] [science]. And suppose I click on english then I want to set the screen to display the first layout again but replacing the text of the view clicked
first layout -> [english] [click].
Now The Problem
I have set up the first layout as main_layout. Now I need to know how can a display the second layout in my fragment_layout and then return back to the main_activity. I want to save the instance of the main_layout as it goes from main to fragment and back to main.
Function called on clicking first layout's text view
View.OnClickListener timetable_click_listen = new View.OnClickListener() {
#Override
public void onClick(View timetable_viewtext) {
setContentView(R.layout.fragment_time_table);
int no_subjects;
/*opens the database and finds out the number of subjects user has entered
Opening database and getting the number of subjects*/
SQLiteDatabase db = openOrCreateDatabase("DATABASE",MODE_PRIVATE,null);
if(db==null)
{
Log.d("Error in TimeTable","There was a error in Opening Database");
}
else{
Log.d("Inside TimeTable Onclick","Opening Database");
}
Cursor c= db.rawQuery("SELECT Num_subjects FROM DETAILS;",null);
c.moveToFirst();
no_subjects = c.getInt(c.getColumnIndex("Num_subjects"));
c.close();
/*Getting the names of the subjects so as to put that name
* as the button's text
*/
String[] name = new String[no_subjects];
c = db.rawQuery("SELECT * FROM SUBJECTS;",null);
c.moveToFirst();
for(int i=0;i<no_subjects;i++)
{
name[i] = c.getString(c.getColumnIndex("Name"));
c.moveToNext();
}
c.close();
db.close();
LinearLayout linearlayout = (LinearLayout) findViewById(R.id.timetable_fragment);
TextView ed;
List<TextView> allEds = new ArrayList<TextView>();
for (int i = 0; i < no_subjects; i++) {
ed = new TextView(TimeTable.this);
allEds.add(ed);
ed.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
ed.setId(1000+i);
ed.setText(name[i]);
tempId = timetable_viewtext.getId();
ed.setClickable(true);
ed.setOnClickListener(subname_click_listen);
((LinearLayout)linearlayout).addView(ed);
}
}
};
Now I am not understanding what to do in the function of the second layout's view.onclick()
Thanks in advance
You should probably use a FragmentManager and a FragmentTransaction. To do this you will need to extend the Fragment class. For example, you might want to make a Fragment to display each layout. These fragments will have their own layout file so you can customize how they look. You will need to provide a container to hold the fragments. I used a FrameLayout called fragment_container. To initialize the fragment, use the FragmentTransaction.add() method and use the FragmentTransaction.replace() method to switch between them.
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
MyFragment fragment = new MyFragment();
ft.add(R.id.fragment_container, fragment);
ft.commit();
Check out the API for more info: FragmentTransaction
Related
I am new to the Android and I am currently working on my android project.
I want to do this...
On the first Activity, the user will enter the number of strings he/she wants to input. For example, 3. (I am already done with this.)
And then, on the second activity, three edit text will appear for the entering the first, second and third string based on the user input in the first activity. If he/she enters 2, two edit text will appear on the second Java Activity. (How to do this one?)
In your Activity1, pass the user's entry to the next activity:
int userSelectedVal=somevalue;
Intent mIntent = new Intent(Activity1.this, Activity2.class);
mIntent.putExtra("userSelectedVal", userSelectedVal);
startActivity(mIntent);
In your Activity2, retrieve this value and programmatically add the Edittext's depending on this value:
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
int noOfEditTexts = extras.getInt("userSelectedVal");
LinearLayout mLinearlayout = new LinearLayout(this);
// specifying vertical orientation
mLinearlayout.setOrientation(LinearLayout.VERTICAL);
// creating LayoutParams
LayoutParams mLayoutParam = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
// set LinearLayout as a root element of the screen
setContentView(mLinearlayout, mLayoutParam);
for (int i = 0; i < noOfEditTexts; i++) {
EditText mEditText = new EditText(context); // Pass it an Activity or Context
myEditText.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
mLinearlayout.addView(mEditText);
}
}
I am developing an app in Android. I am using a flow to take information form the user. To build the flow I am using few fragments. There are five steps and I am using five fragments. I am using another fragment to show the previous records he saved using list view. In my activity I am using a button named Expand. The button Expand is used to show the previous records using fragment. When the user clicks on the button Expand the fragment will take place and the Expand button text will be set to Hide. When the button text is Hide, if the user clicks on the button again the fragment will be removed from the stack and the previous fragment added to the back stack will be shown.
For example let us assume that I have five fragments named FragmentA, FragmentB, FragmentC, FragmentD, FragmentE and another fragment named ProjectRowsFragment which will be used to show the records previously saved in a ListView on the click event of the button named Expand.
Let us assume that the user is in FragmentC and he clicked on the Expand button. What will happen is that FragmentC will be replaced and ProjectRowsFragment will be added. If the user clicks on the button again the ProjectRowsFragment will be replaced and the FragmentC will come in from back stack. If it was FragmentD then it will be replaced and ProjectRowsFragment will be added and if user clicks on the button again ProjectRowsFragment will be replaced and FragmentD will come in from back stack.
I have done with the transactions.
What I want is that I want animation to be added while the ProjectRowsFragment (The fragment I am using to show the records) is shown and replaced. When it is shown it will slide down from the top and then when it is removed from the back stack it will slide up.
After trying a lot I accomplished the slide down effect, but how can I get the slide up animation.
Here is my codes.
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(R.animator.slide_in_from_top, 0, R.animator.slide_in_from_bottom, 0);
fragmentTransaction.replace(R.id.fragment_container, ProjectRowsFragment.newInstance(this.projectId));
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
projectRowsExpanded = true;
slide_in_from_top.xml file is
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true" >
<objectAnimator
android:duration="600"
android:propertyName="y"
android:valueFrom="-1280"
android:valueTo="0"
android:valueType="floatType" />
</set>
Here i have three images to visualize
Initial Step
If the user clicks on the button indicated a list will be placed.
If the user clicks again in the indicated button.
Instead of applying custom animations to fragment, you can add animation to your FrameLayout, by passing your fragment container view to following functions to expand and collapse:
FrameLayout v = (FrameLayout) findViewById(R.id.fragment_container);
expand(v); //To Expand
collapse(v); //To Collapse
public static void expand(final View v) {
v.measure(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
final int targetHeight = v.getMeasuredHeight();
v.getLayoutParams().height = 1;
v.setVisibility(View.VISIBLE);
Animation a = new Animation() {
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
v.getLayoutParams().height = interpolatedTime == 1
? ViewGroup.LayoutParams.WRAP_CONTENT
: (int) (targetHeight * interpolatedTime);
v.requestLayout();
}
#Override
public boolean willChangeBounds() {
return true;
}
};
a.setDuration((int) (targetHeight / v.getContext().getResources().getDisplayMetrics().density));
v.startAnimation(a);
}
public static void collapse(final View v) {
final int initialHeight = v.getMeasuredHeight();
Animation a = new Animation() {
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
if (interpolatedTime == 1) {
v.setVisibility(View.GONE);
} else {
v.getLayoutParams().height = initialHeight - (int) (initialHeight * interpolatedTime);
v.requestLayout();
}
}
#Override
public boolean willChangeBounds() {
return true;
}
};
a.setDuration((int) (initialHeight / v.getContext().getResources().getDisplayMetrics().density));
v.startAnimation(a);
}
I am making an application which uses ListView to show DB elements. But in the first opening or when user will delete everything DB will be empty and then ListView will show blank screen. I want to show a message when it happens. Not only TextView but also Button. For example "DB now empty. Click on button and try to add some records". ListView 's setEmptyView method allows to add only TextView . Is it really possible to create a layout and show it when ListView is empty?
You can use the property setEmptyView.
If the list is empty and your desired display.
ListView listView = (ListView) findViewById(R.id.lst);
View child = getLayoutInflater().inflate(R.layout.empty_view, null);
((ViewGroup)listView.getParent()).addView(child);
listView.setEmptyView(child);
You can dynamically add a button in the activity layout if your list is empty.
Set onClickListner on the button and override the onClick().
Refer below code:
LinearLayout linear = (LinearLayout)findViewById(R.id.layout);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
Button btn = new Button(this);
btn.setId("btnDynamic");
btn.setText("Go to create entry page");
linear.addView(btn, params);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(view.getContext(),
"Button clicked index = " + id_, Toast.LENGTH_SHORT)
.show();
}
});
Let me know if this helps.
You can pre-define a layout containing text view and and button as you stated in your question and set it's visibility = gone in your xml or in java code. When the List View will be empty you can set visibility the visibility of the listview.setVisibility(View.GONE) and set your's layout (containing button and a textview) layout.setVisibility(View.VISIBLE)
I have three fragments which are bound to Tabs as you swipe from TabA to TabB to TabC and it respectively loads FragA, FragB and FragC using ViewPager(Hope you understand this part). This swipe Tabs works just fine but I have a few fixed buttons attached to the bottom of the layout and when each button is clicked i want to load a new fragment to replace any of the Fragment A, B or C. The replacement works fine but when i return to the replaced/previous Fragment all the UI components on that layout completely disappears and it does not indicate if it has been paused, stopped or destroyed. Heres the Code:
Replacing previous Fragment Code:
if(actionBar.isShowing())
{
actionBar.hide();
}
FragmentManager fms = getSupportFragmentManager();
FragmentTransaction fts = fms.beginTransaction();
search s = new search();
if(getCurrentDisplayFragment() == Type1)
{
setcurrentItem(viewPager.getCurrentItem());
Fragment frgs = mAdapter.getItem(viewPager.getCurrentItem());
viewPager.removeViewAt(viewPager.getCurrentItem());
frgs.setUserVisibleHint(false);
Log.i("if say", "Not Responding");
}
fts.replace(R.id.hoster, s);
fts.addToBackStack("search");
fts.commit();
setCurrentDisplayFragment(s,Type2);
The setCurrentDisplayFragment(s,Type2); i built that code to help indicate which fragment is being replaced and what measures to take. S is a Fragment and Type2 is a string
Thus when the back button is pressed i want to return back to any of the Fragments A, B or C that was previously replaced.
Here is the code:
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
//super.onBackPressed();
Log.i("event in back","I have been presssed ");
if(getCurrentDisplayFragment() == Type2)
{
actionBar.show();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
fm.popBackStack();
ft.remove(getCurrentDisplayFragment(Type2));
ft.commit();
viewPager.setCurrentItem(getcurrentItem());
actionBar.setSelectedNavigationItem(getcurrentItem());
Fragment frags = mAdapter.getItem(viewPager.getCurrentItem());
frags.setUserVisibleHint(true);
setCurrentDisplayFragment(frags, Type1);
}
else
{
}
}
Though some variable names and method declaration are not shown but you should get the picture of what am doing because all declarations have been done. its just The Replacement and retaining of their UI states thats giving me a problem.
Why are you complicating this so much? If you want to replace any of the fragments in the view pager, then just replace the view pager. It would be a lot easier if you would have a fragment holding the view pager with the tabs and when the bottom buttons are pressed, you just replace the fragment holding the view pager with the new fragment. In this way you won't need to do anything when the back button will be pressed.
I have a database with team names and team numbers(both stored as strings - the numbers sometimes have letters in them)
I want it so when you click the "Open" button, it'll bring up a popup that will have all of the teams' names and numbers, and if you click one, it will close the popup and set both editText's to the name & number.
Dialog d = new Dialog(this);
ScoutingFormData info = new ScoutingFormData(this);
info.open();
ScrollView scr = info.getData();
info.close();
d.addContentView(scr, null);
d.show();
That's from the main program, when you click "Open", this happens. ScoutingFormData is my SQLite database, and here's getData:
public ScrollView getData() {
String[] columns=new String[]{KEY_ROWID,KEY_NAME,KEY_NUM};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
ScrollView result=new ScrollView(null);
int iID = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iNum = c.getColumnIndex(KEY_NUM);
LinearLayout vertlay = new LinearLayout(null);
vertlay.setOrientation(LinearLayout.VERTICAL);
for (c.moveToFirst(); !c.isAfterLast();c.moveToNext()){
TextView tv=new TextView(null);
tv.setText(c.getString(iNum)+" "+c.getString(iName));
vertlay.addView(tv);
}
result.addView(vertlay);
return result;
}
So this builds the dialog, but how do I make it so the main program(the top code) will know when one of these TextViews have been clicked?
Side question: when making a View(like LinearLayout vertlay = new LinearLayout(null);), what context am I supposed to be using? I don't fully understand what a 'context' is, so I'm really at a loss of what to replace "null" with.
How do I make it so the main program(the top code) will know when one of these TextViews have been clicked?
Simply make tv clickable and add an OnClickListener.
Side question: what context am I supposed to be using?
You hinted that getData() is in your database adapter class ScoutingFormData, save a reference to the Context passed to the Constructor and reuse it later:
private Context mContext;
public ScoutingFormData(Context context) {
mContext = context;
}
All together:
TextView tv=new TextView(mContext);
tv.setClickable(true);
tv.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// Do something
}
});