Android Fragments 在 FragmentTransaction 后恢复 TextView

Android fragments restore TextView after FragmentTransaction

我有 2 个片段:FragmentAFragmentB。这两个片段具有基本相同的代码,如下所示:

public class FragmentB extends Fragment{

    private TextView textView;
    private EditText editText;
    private Button button;

    boolean visible = true;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState){
        final View rootView = inflater.inflate(R.layout.test_fragment, container, false);

        if (textView != null)
            Log.e("FragmentB", "Text was: " + textView.getText().toString());

        textView = (TextView) rootView.findViewById(R.id.textView);
        editText = (EditText) rootView.findViewById(R.id.editText);
        button = (Button) rootView.findViewById(R.id.button);
        ((TextView)rootView.findViewById(R.id.fragment)).setText("Fragment B");

        button.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                Log.e("FragmentB", "Set text: " + editText.getText());
                textView.setText(editText.getText());
                visible = !visible;
                textView.setVisibility(visible ? View.VISIBLE : View.INVISIBLE);
            }
        });

        Log.e("FragmentB", "Text now: " + textView.getText());

        return rootView;
    }
}

为了在 2 个片段之间切换,我调用了 fragmentTransaction.replace(R.id.main_content_frame, currentFragment);,其中 currentFragment 与应用程序启动时创建的实例相同。问题是每当我按下 FragmentB 中的按钮隐藏 TextView,切换到 FragmentA,然后返回到 FragmentB,TextView又可见了,虽然我还是想隐藏。此外,如果我再来回一次,TextView 中的文本也会重置,但只有在来回两次之后。

如何在片段之间切换时保持片段的状态?

我已经尝试使用 onSaveInstanceState()onViewStateRestored(),但是 onViewStateRestored() 总是在 Bundle 设置为 null 的情况下被调用。为什么会这样?

代码如下:

@Override
public void onViewStateRestored(Bundle savedInstanceState){
    Log.e("FragmentB", "Bundle: " + savedInstanceState);

    super.onViewStateRestored(savedInstanceState);
    try{
        textView.setText(savedInstanceState.getString("text"));
    }catch (NullPointerException e){
        e.printStackTrace();
    }

    Log.e("FragmentB", "Bundle: " + savedInstanceState);
    Log.e("FragmentB", "onViewStateRestored");
}

@Override
public void onSaveInstanceState(Bundle outState){
    super.onSaveInstanceState(outState);
    outState.putString("text", textView.getText().toString());
    Log.e("FragmentB", "onSaveInstanceState");
}

使用replace会破坏被替换的片段。因此,每次切换片段时,都会创建一个新片段。使用 hideshow 会更好。

fragmentTransaction.add(fragmentA).add(fragmentB).commit();
fragmentTransaction.show(fragmentA).hide(fragmentB).commit();

尝试使用:

fragmentTransaction.add(R.id.main_content_frame, currentFragment);

而不是:

fragmentTransaction.replace(R.id.main_content_frame, currentFragment);