您可以将单个活动与 top_layout 一起使用,然后在下面有容器,您可以在其中使用 FragmentManager 切换片段。
使用从容器中动态添加和删除的视图可以手动实现类似的结果,当您需要处理具有多个替换视图和回栈的更复杂场景并且您不想自己做时,片段会更有帮助。
布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="@+id/top_layout" />
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
片段 (2x):
public static class GameFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.game_layout, container, false);
}
}
片段添加:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MenuFragment fragment = new MenuFragment();
fragmentTransaction.add(R.id.container, fragment);
fragmentTransaction.commit();
片段切换:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
GameFragment fragment = new GameFragment();
fragmentTransaction.replace(R.id.container, fragment);
fragmentTransaction.commit();
文档:
http://developer.android.com/guide/components/fragments.html