Replace one fragment with an another fragment

前端 未结 8 1554
再見小時候
再見小時候 2020-12-16 19:37

I want to replace an old Fragment with a new Fragment, but i still get the buttons of the old Fragment that is still visible in the ne

8条回答
  •  太阳男子
    2020-12-16 20:13

    In your Activity's onCreate function, you should be calling setContentView(R.layout.main), then when you want to load a Fragment, you choose a ViewParent within R.layout.main. The fragment will become the child of that ViewParent. So the id passed into FragmentTransaction.replace, is the id of the ViewParent in R.layout.main.

    It makes sense that the Button in your allmoods RelativeLayout would remain because the FragmentTransaction.replace function only replaces an existing fragment that is in that container. Everything in R.layout.main will remain. This is how an Activity keeps static content, like drawers or toolbars.

    When you load your "new fragment" you will use the same id. So the "new fragment" replaces the "old fragment" as the new child of the ViewParent within R.layout.main.

    Here is the Fragments API guide.

    Update:

    When you call FragmentTransaction.replace in your Activity's onCreate function, this could be recreating an existing Fragment. Make sure the savedInstanceState (the Bundle passed into onCreate) is null. If the savedInstanceState is not null, then the fragment probably already exists and you can find it like this;

    Fragment f = getFragmentManager().findFragmentByTag(YOUR_FRAGMENT_TAG);
    

    Update 2:

    Here is a guide that should help you. It looks like you could use FragmentPagerAdapter to simplify your fragment transactions.

提交回复
热议问题