How can I show a new Fragment within a single tab?

前端 未结 3 1316
灰色年华
灰色年华 2021-02-04 15:47

I am creating a three tabs that contains one fragment each now I want to replace the first Tab\'s Fragment with a new Fragment within the same Tab. How can I do that with the ta

3条回答
  •  青春惊慌失措
    2021-02-04 16:04

    You have a structure like so:

    TabActivity
     -> Tab1 = FragmentActivity = MainFragment
     -> Tab2          
     -> Tab3          
    

    From inside of MainFragment you are trying to replace the contents of its container (itself).

    It would be best if the MainFragment called a customised TabActivity which in turn called a replace on it's container, either like so (Which may likely fall foul of the same problem as it's basically running the same code from the same place, but it should give you a basic idea of what I'm suggesting):

        Fragment newFragment = new FragmentToChangeTo();
        CustomTabActivity tabActivity = (CustomTabActivity) getActivity();
        tabActivity.changeFragment(newFragment);
    

    If this doesn't work try doing a similar thing but instead of calling the activity directly pass commands to it through Intents & Actions (or Bundles) containing information on what to change which container to.

    I would have preferred to say /why/ Fragments don't work well with Fragment-in-fragment and related intricacies: check here to see why I suggest cutting fragments out of the control of fragments.

提交回复
热议问题