我在使用Fragments和backstack工作时遇到了麻烦。
我有一个带有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>
当我启动使用此布局的Activity时,我将片段添加到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();
然而,当我按下后退按钮时,我会返回主屏幕。谁能告诉我哪里出错了?
答案 0 :(得分:3)
好的我修好了。当我在Intellij中创建Activity
时,它创建了一个ActionBarActivity
的子类。删除ActionBarActivity
并将其替换为Activity
会使片段转换按预期工作。
答案 1 :(得分: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();