Replacing a ListFragment shows the previous list o

2019-07-30 18:33发布

问题:

I have a ListFragment in one of my views, I make a selection in the list and and I replace that fragment with another list. I then again make another selection in this list that replaces this list with another list but that third list always shows on top of the original list like it was never replaced, why would this happen, can I not go three levels deep when replacing fragments?

here is the layout of the view

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


<fragment
    android:id="@+id/frameOne"
    android:name="com.tyczj.bowling.BowlersListFragment"
    android:layout_width="300dp"
    android:layout_height="match_parent"
    android:background="@drawable/list_background_holo" />

<fragment android:name="com.tyczj.bowling.BowlerEntryFrag"
    android:id="@+id/frameTwo"
    android:layout_height="match_parent"
    android:layout_width="fill_parent"/>


</LinearLayout>

frameOne is the fragment that always gets replaced

an Item in the list is selected and I call to replace the list with a new one

ft.replace(R.id.frameOne, infoLf).addToBackStack(null).commit();

then another selection is made in that list so I replace it again like so

ListFragment mBowlersBall = new BowlersBallList(bowlerID);
ft.replace(R.id.frameOne, mBowlersBall);
ft.addToBackStack(null).commit();

and that is when it shows the two lists together like this

回答1:

You aren't properly replacing the fragments. First of all the documentation for the FragmentTransaction.replace() method is pretty clear and it states that the id supplied to it should be the id of the the container whose fragment(s) are to be replaced and not the id of the Fragment to be replaced like you do.

Second, you're mixing static fragments(declared in the xml layout) with dynamic ones(which are added at runtime), which you shouldn't be doing. If you're going to replace that Fragment you'll need to declare that Fragment in code and not in the xml layout(see this response from one of the Android engineers regarding this matter).

So, instead of the frameOne Fragment insert a wrapper layout(like a FrameLayout for example) with an id. In the onCreate method you'll add your initial Fragment(BowlersListFragment) and then, based on a selection in that Fragment, you'll replace it by giving to the FragmentTransaction.replace() method the id of the wrapper layout and the new Fragment instance.