2012-11-04 43 views
1

我在其中一個視圖中有一個ListFragment,我在列表中進行選擇,然後用另一個列表替換該片段。然後,我再次在這個列表中選擇另一個列表,用另一個列表替換這個列表,但是第三個列表總是顯示在原始列表的頂部,就像它從未被替換過一樣,爲什麼會發生這種情況?替換ListFragment顯示新列表中的上一個列表

這裏是視圖

<?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的佈局總是被替換

在列表中的項目被選中,我稱之爲一個新

更換列表中的片段
ft.replace(R.id.frameOne, infoLf).addToBackStack(null).commit(); 

然後在該列表中做出另一個選擇,所以我再次替換它,像這樣

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

那就是當它顯示了兩個列表這樣在一起

enter image description here

回答

0

你沒有正確更換片段。爲FragmentTransaction.replace()方法中的所有文檔的 首先是相當清楚的,它指出提供給它的id應該是id其片段(或多個)被替換而不是Fragmentid是容器換成像你一樣。其次,你將靜態片段(在xml佈局中聲明)與動態片段(在運行時添加)混合在一起,你不應該這樣做。如果您要替換Fragment,則需要在代碼中聲明Fragment,而不是在xml佈局中聲明(有關此問題,請參閱Android工程師的this response)。

因此,而不是frameOneFragment插入包裝佈局(如FrameLayout爲例)與id。在onCreate方法中,您將添加初始FragmentBowlersListFragment),然後根據該Fragment中的選擇,將其替換爲FragmentTransaction.replace()方法包裝器佈局的id和新的Fragment實例。

+0

在某一點上,我確實設置了xml有碎片會去的地方,但如果你點擊返回按鈕碎片將被刪除,你將有一個空白的屏幕,你將不得不按下後退按鈕再次離開活動。我嘗試通過檢查後臺堆棧中添加的碎片的數量並在剩餘的只剩下2個碎片時調用完成的操作來完成該操作,但如果我在完成運行應用程序時啓動的活動中完成操作,現在可以使用'google now'屏幕顯示出來而不是主屏幕 – tyczj

+0

@tyczj我希望你沒有用'addToBackStack()'集合添加初始片段,因爲在這種情況下,Android將顯示你提到的行爲。所以,在'onCreate' **中加入最初的'Fragments' **而不需要**'addToBackStack'。 – Luksprog

相關問題