Android Studio 1.1.2
你好,
我有 MainActivity、TitlesFragment 和 DetailsFragment。
我的 MainActivity 将显示 TitlesFragment,当用户单击标题时,TitlesFragment 将替换为 DetailsFragment。那很好用。但是,当我将 DetailsFragment 添加到 addToBackStack 时。当我单击后退按钮时,它不会显示 TitlesFragment,而是关闭应用程序。
我正在考虑为此需要 2 个 Activity。一个用于 TilesFragment,另一个用于 DetailsFragment?目前我正在尝试通过一个 Activity 来做到这一点?
当前这是我的 MainActivity 代码 fragment (仅显示 fragment 事务)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate");
setContentView(R.layout.activity_main);
/* Load ListFragment */
FragmentManager fragmentManager = getFragmentManager();
Fragment fragment = fragmentManager.findFragmentById(R.id.fragment_container);
/* If the fragment is null then we need to load this fragment */
if(fragment == null) {
fragment = TitlesFragment.newInstance(1234);
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
fragmentTransaction.add(R.id.fragment_container, fragment, "TitlesFragment");
fragmentTransaction.commit();
}
}
@Override
public void onColorPlateSelected(long plateID) {
Log.d(TAG, "onColorPlateSelected: " + plateID);
/* Get the plate ID and pass it to the details fragment */
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
/* Replace the fragment with the new color plate */
fragmentTransaction.replace(R.id.fragment_container, DetailsFragment.newInstance(plateID), "DetailsFragment");
fragmentTransaction.addToBackStack(null);
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
fragmentTransaction.commit();
}
我对 activity_main 的布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
这里 ActivityMain 将替换框架布局中的 fragment 。
我已经看到这是通过处理 OnBackPressed 事件处理程序来实现的。但我想知道如果没有它我是否可以做到?
非常感谢您的任何建议,
最佳答案
尝试将相同的 addToBackStack() 方法添加到您添加到 Activity 中的第一个列表 fragment 。即
fragment = TitlesFragment.newInstance(1234);
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
fragmentTransaction.add(R.id.fragment_container, fragment, "TitlesFragment");
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
这应该可以防止第二个 fragment 在返回堆栈中替换它。
关于android - 当您有一个包含 2 个 fragment 的 Activity 时,将 fragment 添加到 addToBackstack,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28153397/