How do I duplicate fragments? - android

My FragmentActivity loops and creates 8 Fragments from the same xml and activity. The fragment has a TextView, by passing parameters to the Fragment, I want to display different text inside each TextView of the Fragments. With this method, I can save creating 139 identical fragments with different texts.
Problem, all 8 fragment's TextView changes when I setText(), because they all share the same template (xml and activity).
Solution - see my answer below.
Extremis

It's because when you duplicate your Fragment, you refer to the same view for each fragment you create. You have to change the id of the fragment. If you don't do that you call the same fragment all the time.
Final Answer : On onCreateView method
private static int id = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
LinearLayout mLinearLayout = new LinearLayout(this);
TextView mTextView = new TextView(this);
mTexTView.setId(Id);
id++;
mLinearLayout.addView(mTextView);
return mLinearLayout;
}
After you can use the id of your textview and set the text.

Okay, so I've learned that something was wrong in my code when I tried to duplicate fragments in th way attempted above.
My Solution
I created a new dummy Android project and selected the Navigation type as Scrollable Tabs + Swipe.
I then learned that it had 1 activity:
main.java - whcih extends:
FragmentActivity
and, 2 layout's:
main.xml - which contained:
<android.support.v4.view.ViewPager> , and
<android.support.v4.view.PagerTitleStrip>
Fragment.xml - which contained:
TextView
By adjusting the adapter, I was able to create unique Fragments based on the Same layout (xml).
So ultimately - Create a new dummy project with the Scrollable Tabs + Swipe and adjust your code based on that example.
Hope this help.
Extremis

Related

Android add editText proggramatically onClick

so I know the onClick part is quite useless, but just in case it does change anything, ive put it there. so ive got the onClick, and I would like it to add the editText to the current activity, which is called activity_calculation.
I currently have this code which I got from another question :
public void addCalc(View view){
EditText myEditText = new EditText(context); // Pass it an Activity or Context
myEditText.setLayoutParams(new LinearLayoutCompat.LayoutParams(MATCH_PARENT,WRAP_CONTENT)); // Pass two args; must be LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, or an integer pixel value.
activity_calculation.addView(myEditText);
}
any help would be appreciated. maybe you can see what ive done wrong
First get a reference to the activity's root layout. To do this add an id attribute to your activity layout file's root layout. eg :
<LinearLayout
android:id="+id/rootLayout" />
Then, get a reference to it and add the created EditText.
//If your root layout is a RelativeLayout, use that instead
LinearLayout rootView = (LinearLayout) findViewById(R.id.rootLayout);
EditText myEditText = new EditText(rootView.getContext());
myEditText.setLayoutParams(new LinearLayoutCompat.LayoutParams(MATCH_PARENT,WRAP_CONTENT));
rootView.addView(myEditText);

Change fragment layout dynamically instead of replacing fragments Android SDK

I'm trying make an app that displays a big amount of text and images in a specific layout when the user clicks on a corresponding listview item. Since I want specific .xml layouts for separate 'chapters', I want only the layout of a fragment to change to the corresponding chapter.
Googling tells me I can do this with fragments, but as far as I understand, I need separate fragment classes and .xml layouts for every chapter I want to implement. With 2 or 3 chapters, that can be done, but with more chapters that will become I thought, isn't it simpler to just keep two fragments (one with a listview and one with the chapter text), but dynamically change the layout of the second fragment if the user clicks on an item in the listview.
Can this be done with some code like this (just thinking out loud)?
Int[] layouts = {
{R.layout.chapter1, R.layout.chapter2, R.layout.chapter3}
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
index = intent.getIntent("index", 0);
return inflater.inflate(layouts[index], container, false);
}
Or is there another way to achieve this?
Fragments at their core are View wrappers that contains states of Views. You can use them for other purposes like resource handling, but mostly they're just segments of an Activity state. It most likely would not be a good idea to have a Fragment for every single chapter unless each chapter has their own unique state that needs to be kept. However, if the Views are static, then a single Fragment is all you really need.
In this case, you simply have to have a method like this:
public void setChapter(int chapter)
{
Context ctx = getActivity();
if(ctx == null) {
// detached from Activity, so bail.
return;
}
if(chapter > layouts.length) {
return;
}
ViewGroup container = (ViewGroup) getView().findViewById(R.id.chapter_container);
container.removeAllViews();
View chapterInflater = LayoutInflater.from(ctx).inflate(layouts[chapter], container);
}
So this will wipe out all views currently in your container, inflate a new one, and put it in the container (most likely a simple FrameLayout).
The code in the original question can be used to initialize a Fragment if you want to open it at a certain point. onCreate_() methods are called only when the items is being "built" or "created". onCreateView() won't be called again though, so you need a method to change the layout once it's set.

How to populate a list view within a fragment

Hi I have an activity which holds a layout, the layout is divided into two linear layouts. The first layout has 4 buttons. The second one has fragments. Basically with each button press, a new fragment is displayed. All the fragments hold a layout . This layout has an edit text field, a button and a list view. Now everything is working fine, no errors till now. But the problem I am having is , when I try to create a database object and pass the context of the fragment class as parameter in the contructor, it simply shows an error. Here's the code...Please have a look and guide me how can I solve the problem.
String text = null;
EditText enter_task;
// enter_task would be provided with its id, not a problem,
text = enter_task.getText().toString();
try{
// this is where te problem is
// normally I could pass the context of the activity within the constructr of database class as parameter. But since this class is a fragment, I am simply not able to do so.
myDatabase_today = new Database(MyFragment_today.this);
}
The solution which eclispe provides to the problem are:
1-> Change contructor Database(Context) to Database(MyFragment_today).
// here MyFragment_today is the fragment class's name
2-> Create contructor Database(MyFragment_today).
Could anyone please solve this problem. I mean we can pass the activity's context , but not the fragment class's context, then how to proceede further.
Use getActivity() instead of the Fragment class name
myDatabase_today = new Database(getActivity());

Layout in Dynamic Fragments

I'm writing a calculator application in which I would like to be able to switch between 4 modes of calculation: Decimal, Binary, Octal, and Hex. In order to manage the different UIs for the different modes, I have 4 Fragment subclasses in my Activity. Each Fragment has its own XML layout file, in addition to the main XML file for the Activity. I found a guide on the Android Developer site for inflating layouts for Fragments, and I've followed that guide. However, I would like to add listeners and so on to the various components of the layouts, preferably within the onCreateLayout method of the Fragment, or somewhere else where I could do it easily and minimize code duplication.
It appears, however, that when I try to call findViewByID to access one of the inflated Views (after I've called LayoutInflater.inflate, obviously), I get a null return value. This issue occurs whether I call findViewByID from within onCreateLayout or from elsewhere in the Activity (after the Views have, theoretically, been created). What's going wrong here?
One issue I think might be a problem is that I've overloaded the names of the Views between the various Fragment layouts. For example, the "1" button in the Binary layout has the same ID as the "1" button in the Hex layout. Is this allowed, assuming the Binary and Hex layouts are never both part of the Activity at the same time?
Thanks.
I think same id in different layout is not problem in Fragement. First you have to catch the inflated view then find whatever inside this. For example --
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.frg1, container, false);
android.util.Log.v("", "!!!!!!!!!! Frg1 !!!!!!!!!");
Button b = (Button) view.findViewById(R.id.b1);
b.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(getActivity(), "here", Toast.LENGTH_SHORT).show();
}
});
return view;
}

android: a newby GUI question - how to declare viewGroup, without layout XML file?

In the app, I'm struggling with I have a custom view.
I cannot declare it in layout XML file, because I'm going to use in from the activity that holds my custom view instance and I need to have access to it (cannot override findViewById...).
Thereof I decided to declare all of the GUI elements into the Activity.
But I simply cannot make a single step forward, since I even cannot instantiate viewGroup...
This is what I'm trying:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ViewGroup vg = new ViewGroup(this.getApplicationContext());
setContentView(vg);
}
and I get 'Cannot instantiate ViewGroup'...
Can someone give a straight-forward example, of how to declare a viewGroup, that holds views?
The documentation of the class is also not very beginner-friendly... all the examples are focused on describing the layout in a layout XML file...?
Appreciate your efford, giving an example!
[ViewGroup][1] is an abstract class, you cannot instantiate it. It defines a type of classes that will be container to put other views in them. In other words, layouts like LinearLayout of RelativeLayout are ViewGroup. Thus, you could do something like that :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout vg = new LinearLayout(this);
// set the LayoutParams the way you want.
// and add textviews, imageviews, ... here for instance.
setContentView(vg);
}
For the LayoutParams, I think you should start with LayoutParams.Fill_parent

Categories

Resources