简体   繁体   中英

Switching Fragments in TabHost

Here's my layout design:

    MainActivity
         |
    MainFragment
         |
      TabHost
         |
_____________________
|     |     |     |
Tab1  Tab2  Tab3  Tab4
      |
     ft.replace(MainActivityContainer, FragmentThatDoesSomething)
      |
   FragmentThatDoesSomething

As you can see, there's a button that does a ft replace on the main activity container and loads FragmentThatDoesSomething to accomplish a task.

In FragmentThatDoesSomething I want to have a button that goes back to Tab2 of the TabHost and keep the tabs.

I use the activity to transfer data between fragments so in the activity is where I would like to perform some ft transaction to get back to tab2.

What's the easiest way to do this? If I run an ft transaction with the getChildFragmentManager and Tab2's container I run into this problem

because I'm using the support v4 Fragment class.

I would use addToBackStack(null) for my fragment transactions. Then the button defined in FragmentThatDoesSomething could call getActivity.onBackPressed() .

At that point it is just a matter of making sure to save state.

// MainActivity.java
@Override
public void someCallbackMethod(Object obj1, Object obj2) {
    // have MainActivity store your values and Tab2 fragment accesses data
    // through callback references when Tab2.onCreateView() is called.

    onBackPressed();

    // OR retrieve your Tab2 fragment and manually update values here via 
    // some kind of accessor
}

I chose to implement activities as handling nested fragments are a pain.

One gotcha I ran into was sending data back from FragmentThatDoesSomething (now an activity) back to Tab 2. Because Tab 2 is a nested fragment of MainFragment, I had to override onActivityResult in MainFragment to send data back to the child Tab 2. I think its because I'm using the v4 Fragment support class.

I did that using this code.

compile 'com.android.support:design:22.2.0' I thing you need to use above material design library to solve your issue . you can add multiple fragment in one viewPager .

It will provide you more other option to do .

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