2014-02-22 62 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使片段转换按预期工作。

相关问题