android - fragment 如何恢复其 View 状态?

标签 android android-fragments fragment

我正在尝试探索 android 框架如何管理 fragment ,通过我的研究,我了解了很多我不知道的关于 fragment 的新事物,但我一度陷入困境,无法弄清楚如何这正在发生。

请先尝试理解我的场景。它是这样的: 我有一个 Activity ,一个一个地添加两个 fragment 。首次加载 Activity 时,使用以下代码将 fragment A 附加到它:

private void initFirstFragment(){
    Bundle bundle = new Bundle();
    bundle.putString("TEXT_TO_SHOW", "FIRST ACTIVITY\nFIRST DUMMY FRAGMENT");
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.frameLayoutFragmentContainer, FirstDummyFragment.newInstance(bundle), FirstDummyFragment.class.getSimpleName());
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();
}

Fragment A的这些回调方法在加载时被调用

FirstDummyFragment: onCreate: savedInstanceState--->null

FirstDummyFragment: onCreateView: savedInstanceState--->null

FirstDummyFragment: onResume

现在在 fragment A 中,我有一个编辑文本,我在其中键入了一些文本。

当在 Activity 中单击按钮时,使用以下代码将 Fragment B 添加到同一容器中:

public void openSecondFragment() {
    Bundle bundle = new Bundle();
    bundle.putString("TEXT_TO_SHOW", "FIRST ACTIVITY\nSECOND DUMMY FRAGMENT");
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.frameLayoutFragmentContainer, SecondDummyFragment.newInstance(bundle), SecondDummyFragment.class.getSimpleName());
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();
}

添加Fragment B后调用以下回调方法

SecondDummyFragment: onCreate: savedInstanceState--->null

FirstDummyFragment: onDestroyView

SecondDummyFragment: onCreateView

SecondDummyFragment: onResume

当我按下后退按钮时,Fragment B 被销毁,Fragment A 出现在前台,下面的回调方法被调用

SecondDummyFragment: onDestroyView

SecondDummyFragment: onDestroy

SecondDummyFragment: onDetach

FirstDummyFragment: onCreateView: savedInstanceState--->null

FirstDummyFragment: onResume

并且 fragment A 的编辑文本包含我在添加 fragment B 之前输入的相同文本。我很困惑 android 如何恢复 fragment A 的 View 状态,即使 savedInstanceState 为 null 并且 onCreateView 在 fragment 时返回一个全新的 View 对象再次创建 A。

最佳答案

终于找到答案了 here .

Android 就是这样设计的。在这种情况下,View State Saving/Restoring 在 Fragment 内部被调用。因此,每个在内部实现了 View 状态保存/恢复的 View ,例如带有 android:freezeText="true"的 EditText 或 TextView,将自动保存并恢复状态。使其显示与之前完全相同。

关于android - fragment 如何恢复其 View 状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41536274/

相关文章:

运行 Shell 脚本的 Android 程序

android - 用于 android 的 loopj 中的 Cookie

android - 无法保存和恢复嵌套 fragment ?

java - 使用两个 fragment 库

Android fragment WebView

android - 用Android中的 fragment 问题替换线性布局

android - 拦截来自 Android WebView 的*所有*请求

android - 更改字符串中的文本颜色?

java - 方法不会覆盖其父类(super class)中的方法。安卓 fragment

android - 如何创建动态选项卡并将不同的产品加载到每个 fragment ?