2014-02-22 92 views
1

我在獲取片段和後臺工作時遇到了問題。片段沒有添加到後臺堆棧

我有一個的FrameLayout佈局舉辦各種片段和另一個片段:

<LinearLayout 
xmlns:tools="http://schemas.android.com/tools" 
android:orientation="vertical" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
xmlns:android="http://schemas.android.com/apk/res/android"> 

<FrameLayout 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:id="@+id/filterableListContainer" 
    android:layout_weight="50"> 
</FrameLayout> 


<fragment class="com.facetoe.remotempd.fragments.PlayerBarFragment" 
      android:id="@+id/playerBarFragment" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_weight="1" 
      tools:layout="@layout/player_bar"/> 
</LinearLayout> 

當我開始使用此佈局我的片段添加到FrameLayout裏,像這樣的活動:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_test); 
    if (findViewById(R.id.filterableListContainer) != null) { 

     // However, if we're being restored from a previous state, 
     // then we don't need to do anything and should return or else 
     // we could end up with overlapping fragments. 
     if (savedInstanceState != null) { 
      return; 
     } 

     // Create a new Fragment to be placed in the activity layout 
     ArtistListFragment listFragment = new ArtistListFragment(); 

     // Add the fragment to the 'fragment_container' FrameLayout 
     FragmentTransaction ft = getFragmentManager().beginTransaction(); 
     ft.replace(R.id.filterableListContainer, listFragment); 
     ft.addToBackStack(null); 
     ft.commit(); 
    } else { 
     Log.e(TAG, "Couldn't find filterableListFragment"); 
    } 

} 

當用戶點擊一個項目,我試圖與該代碼替換片段:

  ArtistAlbumsListFragment fragment = new ArtistAlbumsListFragment(getActivity(), albums); 
     FragmentTransaction ft = getFragmentManager().beginTransaction(); 
     ft.replace(R.id.filterableListContainer, fragment); 
     ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); 
     ft.addToBackStack(null); 
     ft.commit(); 

但是,當我按下後退按鈕時,我會返回到主屏幕。誰能告訴我我要去哪裏?

+2

您需要將片段添加到backstack中 – Raghunandan

+0

不是ft.addToBackStack(null);添加片段到後臺? – facetoe

+0

它確實會起作用 – Raghunandan

回答

0

不要添加ft.addToBackStack(null)這個語句。

ArtistAlbumsListFragment fragment = new ArtistAlbumsListFragment(getActivity(),albums); FragmentTransaction ft = getFragmentManager()。beginTransaction(); ft.replace(R.id.filterableListContainer,fragment); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); ft.commit();

+0

恐怕這對我也不起作用。 – facetoe

+0

你正在做片段之間的轉換嗎? – MohsinSyd

+0

我想通了,由於某種原因,子類ActionBarActivity阻止片段被正確添加到堆棧。 – facetoe

3

好的我修好了。當我在Intellij中創建Activity時,它創建了一個ActionBarActivity的子類。刪除ActionBarActivity並將其替換爲Activity使片段轉換按預期工作。

相關問題