Fragment Inside Fragment

2019-01-01 11:48发布

I need help regarding working on fragment inside fragment, actually I am facing a problem on pressing back button. Application Main screen has buttons and pressing on each button view replace with new fragment(and that fragment contain inside another fragment), dynamically adding/replacing fragment is working fine, by pressing button1 fragment replaced, same happens when pressing button, but if I press the button again, got an exception:

"Duplicate id 0x7f05000a, tag null, or parent id 0x7f050009 with
another fragment for com........ fragmentname"

means fragment or inner fragments are already added and I am trying to add them again, anybody has idea how to work with fragment inside fragment and moving back and forth without any problem, thanks for the support.

MainActivity, where fragments are dynamical added and replaced.

   public class FragmentInsideFragmentTestActivity extends Activity {

   private Button button1;
   private Button button2;
   private Button button3;
   private Button button4;


   /** Called when the activity is first created. */
  @Override
   public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);

   button1 =(Button) this.findViewById(R.id.button1);
   button1.setOnClickListener(new View.OnClickListener() {
       public void onClick(View view) {
           onButtonClick(view);

           }
   });

   button2 =(Button) this.findViewById(R.id.button2);
   button2.setOnClickListener(new View.OnClickListener() {
       public void onClick(View view) {
           onButtonClick(view);

           }
   });

   button3 =(Button) this.findViewById(R.id.button3);
   button3.setOnClickListener(new View.OnClickListener() {
       public void onClick(View view) {
           onButtonClick(view);

           }
   });

   button4 =(Button) this.findViewById(R.id.button4);
   button4.setOnClickListener(new View.OnClickListener() {
       public void onClick(View view) {
           onButtonClick(view);

           }
   });

    }

   public void onButtonClick(View v) {
           Fragment fg;
           switch (v.getId()) {
           case R.id.button1:
                   fg=FirstFragment.newInstance();
                   replaceFragment(fg);
                   break;
           case R.id.button2:
                   fg=SecondFragment.newInstance();
                   replaceFragment(fg);
                   break;
           case R.id.button3:
                   fg=FirstFragment.newInstance();
                   replaceFragment(fg);
                   break;
           case R.id.button4:
                   fg=SecondFragment.newInstance();
                   replaceFragment(fg);
                   break;
           }
   }

   private void replaceFragment(Fragment newFragment) {

   FragmentTransaction trasection =
   getFragmentManager().beginTransaction();
   if(!newFragment.isAdded()){
           try{
                   //FragmentTransaction trasection =
           getFragmentManager().beginTransaction();
           trasection.replace(R.id.linearLayout2, newFragment);
           trasection.addToBackStack(null);
           trasection.commit();

           }catch (Exception e) {
                           // TODO: handle exception
                    //AppConstants.printLog(e.getMessage());

                   }
   }else
           trasection.show(newFragment);

      }
    }

Here is Layout: main.xml

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"

   <LinearLayout android:id="@+id/linearLayout1"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:orientation="horizontal">
           <Button android:layout_width="wrap_content"
                   android:id="@+id/button1"
                   android:layout_height="wrap_content"
                   android:text="Button1"></Button>
           <Button android:text="Button2"
                   android:id="@+id/button2"
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"></Button>
           <Button android:text="Button3"
                   android:id="@+id/button3"
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"></Button>
           <Button android:text="Button4"
                   android:id="@+id/button4"
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"></Button>
   </LinearLayout>

  <LinearLayout android:id="@+id/linearLayout2"
   android:layout_width="match_parent"
    android:layout_height="wrap_content"
   android:orientation="horizontal"></LinearLayout>
     </LinearLayout>

Hope I tried to clear my problem.

13条回答
裙下三千臣
2楼-- · 2019-01-01 12:43

Fragments can be added inside other fragments but then you will need to remove it from parent Fragment each time when onDestroyView() method of parent fragment is called. And again add it in Parent Fragment's OnCreateView() method.

Just do like this :

@Override
    public void onDestroyView()
    {
                FragmentManager mFragmentMgr= getFragmentManager();
        FragmentTransaction mTransaction = mFragmentMgr.beginTransaction();
                Fragment childFragment =mFragmentMgr.findFragmentByTag("qa_fragment")
        mTransaction.remove(childFragment);
        mTransaction.commit();
        super.onDestroyView();
    }
查看更多
与君花间醉酒
3楼-- · 2019-01-01 12:44

Its nothing complicated. We cannot use getFragmentManager() here. For using Fragments inside a Fragment, we use getChildFragmentManager(). Rest will be the same.

查看更多
步步皆殇っ
4楼-- · 2019-01-01 12:45

AFAIK, fragments cannot hold other fragments.


UPDATE

With current versions of the Android Support package -- or native fragments on API Level 17 and higher -- you can nest fragments, by means of getChildFragmentManager(). Note that this means that you need to use the Android Support package version of fragments on API Levels 11-16, because even though there is a native version of fragments on those devices, that version does not have getChildFragmentManager().

查看更多
公子世无双
5楼-- · 2019-01-01 12:46

There is no support for MapFragment, Android team says is working on it since Android 3.0. Here more information about the issue But what you can do it by creating a Fragment that returns a MapActivity. Here is a code example. Thanks to inazaruk:

How it works :

  • MainFragmentActivity is the activity that extends FragmentActivity and hosts two MapFragments.
  • MyMapActivity extends MapActivity and has MapView.
  • LocalActivityManagerFragment hosts LocalActivityManager.
  • MyMapFragment extends LocalActivityManagerFragment and with help of TabHost creates internal instance of MyMapActivity.

If you have any doubt please let me know

查看更多
何处买醉
6楼-- · 2019-01-01 12:49

Since Android 4.2 (API 17) nested fragments become available http://developer.android.com/about/versions/android-4.2.html#NestedFragments

To place fragment inside other fragment use getChildFragmentManager()

It also available in support library!

查看更多
深知你不懂我心
7楼-- · 2019-01-01 12:49

That may help those who works on Kotlin you can use extension function so create a kotlin file let's say "util.kt" and add this piece of code

fun Fragment.addChildFragment(fragment: Fragment, frameId: Int) {

    val transaction = childFragmentManager.beginTransaction()
    transaction.replace(frameId, fragment).commit()
}

Let's say this is the class of the child

class InputFieldPresentation: Fragment()
{
    var views: View? = null
    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        views = inflater!!.inflate(R.layout.input_field_frag, container, false)
        return views
    }

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        ...
    }
    ...
}

Now you can add the children to the father fragment like this

 FatherPresentation:Fragment()
{
  ...

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val fieldFragment= InputFieldPresentation()
        addChildFragment(fieldFragment,R.id.fragmet_field)
    }
...
}

where R.id.fragmet_field is the id of the layout which will contain the fragment.This lyout is inside the father fragment of course. Here is an example

father_fragment.xml:

<LinearLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android"
    >

    ...

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:id="@+id/fragmet_field"
            android:orientation="vertical"
            >
        </LinearLayout>
    ...

    </LinearLayout>
查看更多
登录 后发表回答