这是否可以在再次调用片段时恢复片段 UI 中的数据状态?

Is this possible to restore the state of data in UI of fragment while calling fragment again?

如果我有片段 A 和片段 B。我使用以下代码从 A 调用片段 B

FragmentManager fragmentManager =getFragmentManager();
    FragmentTransaction fragmentTransaction =
            fragmentManager.beginTransaction();


    fragmentTransaction.add(R.id.frame_step, fragment,TAG).hide(SourceFragment.this).addToBackStack((SourceFragment.class.getName()));
    fragmentTransaction.commit();

现在在 Fragment B 中我有 EditText 并且我在其中输入了 "Hello",如果我从 Fragment B 按下后退按钮然后根据 getSupportFragmentManager().popBackStack(); 它将恢复 Fragment A

现在,如果我再次从 Fragment A 调用 Fragment B,我希望 FragmentB 不会再次创建,但我仍然可以在 EditText 中看到 "Hello"。

注意——我不想为此使用变量或共享首选项,因为我有多个片段和多个视图,比如一个大表单。有没有什么可以只从其恢复状态调用片段而不是再次调用它,或者我是否可以检查这个片段是否已经创建。 提前致谢

你想要的都有可能。您需要在前向导航之前保存片段状态,并在从后台堆栈恢复片段后恢复它。

在片段中

private Bundle savedState = null;

 @Override
    public void onDestroyView() {
        super.onDestroyView();
        savedState = saveState();
    }

    private Bundle saveState() { /* called either from onDestroyView() or onSaveInstanceState() */
        Bundle state = new Bundle();
        state.putCharSequence("TEXT_HELLO_WORD", helloWordTextView.getText());
        return state;
    }

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        /* (...) */

        if(savedInstanceState != null && savedState == null) {
            savedState = savedInstanceState.getBundle("FRAGMENT_HELLO_WORD");
        }
        if(savedState != null) {
         helloWordTextView.setText(savedState.getCharSequence("TEXT_HELLO_WORD"));
        }
        savedState = null;

        /* (...) */
        return view;
    }
...
@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    //Save the fragment's state here somehow like this
    outState.putBundle("FRAGMENT_HELLO_WORD", (savedState != null) ? savedState : saveState());
}

在Activity

public void onCreate(Bundle savedInstanceState) {
    ...
    if (savedInstanceState != null) {
        //Restore the fragment's instance
        mContent = getSupportFragmentManager().getFragment(savedInstanceState, "myFragmentName");
        ...
    }
    ...
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    //Save the fragment's instance
    getSupportFragmentManager().putFragment(outState, "myFragmentName", mContent);
}

答案编译自here and here

希望对您有所帮助。

在 2019 年实现此目标的最佳方法是使用支持片段的共享视图模型。如果数据在这些片段之间共享,您可以随时从任何片段访问 ViewModel 中的数据。我们唯一需要记住的是在 activity 上下文中初始化 ViewModel。 参考 https://developer.android.com/topic/libraries/architecture/viewmodel#sharing