简体   繁体   中英

Android: Multiple Fragments from same XML file

I have a view pager that has a page for each subject in an array (English, Maths, Science, etc). The fragments in the view pager are all created from the same XML file. These fragments then have fragments added inside of them. As all the parents inflate from the same XML file, I can not specify which fragment I want to add the child fragment to. I was wondering if their was a way to do this - Narrow the scope of the id maybe??

First. I suggest you to try to avoid child fragment, if you really doesn't have very good reason to use them.

But I don't understand where is problem. I don't see any problem if more fragment use the same XML for the inflate. You can call setArguments() on all parent fragment and put here some Bundle which can be used to recognize which fragment it is inside of it by getArguments() .

I think you want to implement multiple fragments with the capability to manipulate them depending on user selections. There is Google link Fragments

Review these code on that web page:

  1. The many samples of Fragment and FragmentTransaction
  2. Look at method showDetails in class TitlesFragment , for example.

If you want a working sample, look at Working with Android Fragments . Snippet from the webpage:

<LinearLayout
  android:layout_width="wrap_content"
  android:layout_height="match_parent">
  <fragment
    android:id="@+id/headFrag"
    android:name="com.intertech.HeaderFrag"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"/>
  <fragment
    android:id="@+id/bodyFrag"
    android:name="com.intertech.BodyFrag"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"/>
</LinearLayout>

And the code

...
    FragmentManager fragmentManager = getFragmentManager ();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction ();
    // work here to change Activity fragments (add, remove, etc.).
    fragmentTransaction.add (R.id.myFrame, myFrag);
    fragmentTransaction.commit ();

From above, notice there are 2 fragments in the layout. And fragmentTransaction.add method should specify parent container in R.id form.

Someday I may want/need to implement this. So far I implemented show/hide Layouts instead (not regretting it), and they can have IDs for me to manipulate. Have fun and keep us posted, Tommy Kwee.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM