How to programmatically add fragments in a loop to a single activity? - android

Since I don't know how many views I need so I have to create them dynamically. Based on my research that each fragment has to have a container, they can't share (Correct me if i'm wrong), so I need to create view container for each fragment dynamically, then I can have this:
for(int i = 0; i < size ; i ++) {
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.disallowAddToBackStack();
ft.add(new ABCFragment(), TAG).commit();
}
Does anyone know how i can get this working? I'm new to android still.
Thanks!!!!

Define it in xml, it will work as container:-
<RelativeLayout
android:visibility="gone"
android:id="#+id/R.id.container_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/transparents"/>
To get dynamic number of fragments, define different tag name for that:-
for (int i=0;i<size;i++){
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.container_fragment, new DetailFragment(), tag.get(i));
ft.commit();
}
You can give different tag names under tag.get(i)

Related

How to get the reference of a fragment created by FragmentTransaction.replace method

I added a fragment inside an activity by using the following codeļ¼š
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.parent_fragment_container, new FolderStructureFragment());
ft.commit();
My question is how can I get the reference of the added fragment. I have searched a lot of key words related to fragment and FragmentTransaction but didn't find anything close to my requirement which I think is a very basic function and should be offered to us. Any help is much appreciated!
There are the two major possiblities:
You can remember the reference by yourself
By an Tag
By ID
For example (nearly the same for by ID):
ft.replace(R.id.fragment_container, fragment, tagOfFragment);
getSupportFragmentManager().findFragmentByTag(tagOfFragment);
try using the below code.
FolderStructureFragment folderStructureFragment = (FolderStructureFragment)getActivity().getSupportFragmentManager().findFragmentById(R.id.parent_fragment_container);
FolderStructureFragment folderStructureFragment = new FolderStructureFragment();
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.parent_fragment_container, folderStructureFragment);
ft.commit();
Here , folderStructureFragment is reference for newly added fragment.
There is an easy way to get a reference to a fragment any time you need, and that is with a TAG. Whenever you add a fragment you may give it a specific tag, and you may retrieve it anytime you want with that same TAG.
This is how you add it:
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MyFragment myFragment = new MyFragment();
fragmentTransaction.add(R.id.fragment_container, myFragment,"myFragmentTag").commit();
Now let's say, somewhere in the code you need the reference to this fragment, you only need to call the following
MyFragment myFragment = (MyFragment)getSupportFragmentManager().findFragmentByTag("myFragmentTag");
if(myFragment != null && myFragment.isAdded()){ //you should always do this check when you retrieve fragment instances
//do whatever you need with it
}

Adding fragments using for loop

I am very new to programming an android as well. I am trying to add fragments using for loop. Lets say I would like to repeat fragment n-times.
for (int i = 0; i < length; i++)
{
FragmentTransaction fragmentTransaction = this.FragmentManager.BeginTransaction();
Fragment frag = _fragments[1];
fragmentTransaction.Add(Resource.Id.frameForAddressFragment, frag);
fragmentTransaction.AddToBackStack(null);
fragmentTransaction.Commit();
}
I think I have to declare Fragment for every loop with new name?
Am I right?
Could some one show me right approach.
First, I never use Xamarin, but can't you slightly change your code to this? I don't see the point of beginning a new transaction for each and every fragment. Same goes for committing.
FragmentTransaction fragmentTransaction = this.FragmentManager.BeginTransaction();
for (int i = 0; i < length; i++)
{
Fragment frag = _fragments[1];
fragmentTransaction.Add(Resource.Id.frameForAddressFragment, frag);
fragmentTransaction.AddToBackStack(null);
}
fragmentTransaction.Commit();
Second, I don't know if it's a mistake, but you have written Fragment frag = _fragments[1];. I assume you meant Fragment frag = _fragments[i];
Third, is there any problem with your code? As a reminder, your "Resource.Id.frameForAddressFragment" is supposed to be the ID of the container in which you want to add the fragment.
Last, what do you mean by this?
I think I have to declare Fragment for every loop with new name?
What "new name" are you talking about?

FragmentManager add multiple instances of the same Fragment type

I have the need to "stack up" fragments one on top of another. I do this by:
String className = fragment.getClass().getName();
FragmentManager fragmentManager = getChildFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_content, fragment, className);
fragmentTransaction.addToBackStack(className);
fragmentTransaction.commit();
Within:
<FrameLayout
android:id="#+id/fragment_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" />
This all works good as long as the fragments are of different type.
However if I create a second instance of a fragment type that is already there then there is an exception:
java.lang.IllegalStateException: Fragment already added: TestFragment{1184e8a1 #0 id=0x7f0800ef com.test.ui.TestFragment}
How can I add multiple instances of the same fragment?
One requirement is that they are all on top of each other - because few of them have a small margin that lets you see small portion of the fragment underneath.
Thank you for your help!
Layout of parent fragment
<FrameLayout
android:id="#+id/fragment_contentrow"
android:layout_width="match_parent"
android:layout_height="match_parent" />
code in parent fragment to add child fragment
FragmentManager fm = getChildFragmentManager();
for (int x = 1; x < 5; x = x + 1) {
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fragment_contentrow, new MyChildFragment(), "Tag " + x);
ft.addToBackStack(null);
ft.commit();
}
Try to create new instance of your fragment instead of replacing it with the same object over and over again.
fragment = new YourFragment();
fragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_content, fragment, className)
.addToBackStack(className);
.commit();
Also I suggest to change tags between fragments, for example you can add a number to it.

Adding Fragment to containers with the same ID

I have a ViewPager to implement swipe between "holder" Fragments. And inside them I need to add multiple Fragments to their respective containers.
The problem is, Im using FragmentTransaction.add(containerID, fragment);, but since there are multiple holder Fragments in the ViewPager, all the Fragments get added on the same holder Fragment, and not in the one that is calling to add them.
Anyone has an idea on a good practice to go around this problem?
Here is the code where I add the Fragments inside the holder fragment.
arrayFragments = new ArrayList<DiaAgendaFragment>();
DiaAgendaFragment objFragment;
FragmentManager fm = getFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
//this will be set accordingly later for each fragment
Time dataFragment = new Time();
dataFragment.setToNow();
//instantiate and set fragments
for (int i = 0; i < 5; i++) {
objFragment = DiaAgendaFragment.newInstance(5, dataFragment);
arrayFragments.add(objFragment);
//pega a View pelo nome e adiciona o fragment
transaction.add(getActivity().getResources().getIdentifier("agenda5d_activity_fragment"+i, "id", getActivity().getPackageName()), arrayFragments.get(i));
//codigo de teste
dataFragment.monthDay += 1;
}
transaction.commit();
You have to use the child FragmentManager if you want to add Fragments to another Fragment. Using the normal FragmentManager will not work as you found out yourself.
In your Fragment:
FragmentManager manager = getChildFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
...
transaction.commit();

Add fragment into a fragment (nested fragment)

I want to add a youtube fragment into my already existing fragments dynamically. The code I used is below:
// setting the Youtube Player Dynamically
private int setYoutubePlayer(String desc, View view, int prevID,
Bundle input) {
if (desc.indexOf("=") != -1) {
desc = desc.substring(desc.indexOf("=") + "=".length());
} else {
return prevID;
}
final String url = desc;
LinearLayout videoLayout = new LinearLayout(view.getContext());
videoLayout.setOrientation(LinearLayout.VERTICAL);
prevID++;
videoLayout.setId(prevID);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragment.setVideoId(url);
LinearLayout itemLayout = (LinearLayout) view.findViewById(R.id.items);
itemLayout.addView(videoLayout);
fragmentTransaction.add(itemLayout.getId(), fragment,
"youtube fargment " + prevID);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
return prevID;
}
I need to get the youtube fragment in the appropriate fragment. As I checked when always a new fragment get loaded (when swipe between fragments), the new inner fragment needs to be the first loaded fragment.
Any help will be gladly accepted.
SOLVED: Thank you Koby You were right. i had to replace "getActivity().getSupportFragmentManager();" with "getChildFragmentManager()". The problem was apparently the Sherlock library came with a old android v4 support library. I had to update the support library in the Sherlock. It worked for me.....
to create a nested fragment inside a fragment, you should use:
http://developer.android.com/reference/android/app/Fragment.html#getChildFragmentManager()
call the getChildFragmentManager() from the parent fragment,
and do the transaction in the parent to nest the child inside.
https://stackoverflow.com/a/13381825/1693674
tell me if you need more help in doing that...

Categories

Resources