android - 方向更改后如何将 fragment 重新加载到后台堆栈

标签 android android-fragments android-appcompat android-orientation

我的 Android 应用程序有一个注册流程设置和一个 Activity ,我将这些步骤作为 fragment 加载到 Activity 布局中。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    tools:context="com.example.android.ui.RegisterActivity">

    <LinearLayout
        android:id="@+id/register_container"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"></LinearLayout>

</RelativeLayout>

现在每个 fragment 类都实现了一个在 RegisterActivity 中实现的公共(public)接口(interface),以便我知道加载下一步 fragment 并将新 fragment 添加到后台

mFragmentTransaction.addToBackStack(mStepOne.TAG);

现在通过 4 个步骤一切正常,我可以通过这些步骤返回,同时在每个 fragment 中保留输入的数据,如果它保持相同的方向(纵向)

但是一旦我改变方向, fragment View 就会消失

如果我到了第 3 步,我仍然可以点击后退按钮,它会返回并通过查看后台堆栈更改的监听器向我显示本来应该在那里的 fragment

mFragmentManager.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
        @Override
        public void onBackStackChanged() {
            if(mFragmentManager.getBackStackEntryCount() > 0) {
                Log.d("BACK STACK", "TAG (name): " + mFragmentManager.getBackStackEntryAt( (mFragmentManager.getBackStackEntryCount() - 1)).getName());
            }
        }
    });

保留 fragment 的计数和标签,但不保留 View 。 RegisterActivity onCreateView 将术语 fragment 加载到 View 中,它是在通过步骤返回时保留在 View 中的内容。

mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mTerms = new RegisterFragmentTerms();
mFragmentTransaction.add(R.id.register_container, mTerms);
mFragmentTransaction.commit();

在我看来, View 被加载到彼此之上的 RegisterActivity 中,并在方向更改时被清除。有可能解决我想做的事情吗?还是我实现错了?这是我的第一个安卓应用:)

干杯

最佳答案

好像是Activity娱乐引起的。你有没有在你的AndroidManifest.xml中添加android:configChanges="orientation|keyboardHidden|screenSize"到你的Activity? ,如果您将该标志添加到您的 Activity 中,它不会在方向改变时被销毁, fragment 堆栈也不会消失。

关于android - 方向更改后如何将 fragment 重新加载到后台堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28337266/

相关文章:

android - AppCompatButton backgroundTint API < 21

android-5.0-lollipop - ActionBar 中动画 ActionBarDrawerToggle 的颜色

Android 添加边框以编程方式编辑文本

java - 当我通过 NavController.navigateUp() 返回时,为什么我的 fragment *有时* 是空白的?

android - colorButtonNormal没有效果?

java - 订阅者类及其父类(super class)没有带有@subscribe 注释的公共(public)方法

android - 在 MainActivity 内调用导航主机 fragment 上的方法

android - 为什么用户运行 gradlew 的位置会影响输出?

java - 在注释中使用@hide 隐藏方法/类

android - Android 服务和数据通信的最佳方法是什么