理论
使用FragmentTransaction 中的addToBackStack(tag: String): FragmentTransaction 方法来标记要返回的点。 此方法返回 FragmentTransaction 实例仅用于链式能力。
然后从FragmentManager 使用popBackStackImmediate(tag: String, flag: int): void 方法返回。标签是您之前指定的。该标志要么是常量POP_BACK_STACK_INCLUSIVE 以包含标记的事务,要么是0。
示例
下面是一个示例,其布局具有 FrameLayout 和 id content_frame,片段被加载到其中。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<FrameLayout
android:id="@+id/content_frame"
android:layout_below="@id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
以下代码在将布局元素的内容替换为 id content_frame 时,通过片段类名标记片段。
public void loadFragment(final Fragment fragment) {
// create a transaction for transition here
final FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
// put the fragment in place
transaction.replace(R.id.content_frame, fragment);
// this is the part that will cause a fragment to be added to backstack,
// this way we can return to it at any time using this tag
transaction.addToBackStack(fragment.getClass().getName());
transaction.commit();
}
为了完成这个例子,一个方法可以让你在加载时使用标签返回到完全相同的片段。
public void backToFragment(final Fragment fragment) {
// go back to something that was added to the backstack
getSupportFragmentManager().popBackStackImmediate(
fragment.getClass().getName(), 0);
// use 0 or the below constant as flag parameter
// FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
当你真正实现这个时,你可能想要在片段参数上添加一个空检查;-)。