5

我正在尝试创建一个Fragment在显示后保留其状态的内容。

为此,我尝试使用getFragmentManager().saveFragmentInstanceState()inside onPause()& 然后调用setInitialSavedState()inside onCreateView()

我面临的问题是我不知道如何准确使用它们以及何时调用它们。

此外,这两个函数都采用 type 的参数SavedState,我不确定如何使用。

代码:

public class AudioContainerFragmentClass extends Fragment implements
        OnClickListener {

    final String TAG = "AudioContainerFragmentClass";
    private Button bSetName;
    private TextView tvName;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = null;
        try {
            Log.e(TAG, "onCreateView()");
            view = inflater.inflate(R.layout.audio_fragment_container, null);
            bSetName = (Button) view.findViewById(R.id.bSetName);
            tvName = (TextView) view.findViewById(R.id.tvName);
            bSetName.setOnClickListener(this);

            if(savedInstanceState != null){
                setInitialSavedState(/* WHICH SavedState OBJECT TO PASS */);
            }
            Log.e(TAG, "onCreate()");

        } catch (Exception e) {
            Log.e(TAG, "onCreateView(): " + e.toString());
        }
        return view;
    }

    /*
    @Override
    public void onSaveInstanceState(Bundle outState) {
        Log.e(TAG, "onSaveInstanceState()");
        super.onSaveInstanceState(outState);
    }
    */

    @Override
    public void onClick(View v) {
        tvName.setText("sometext");
    }

    @Override
    public void onPause() {
        super.onPause();
        getFragmentManager().saveFragmentInstanceState( /* WHAT TO ADD HERE */);

    }

}
4

1 回答 1

10

只是自己调查一下,并认为我会记录我的发现。

setInitialSavedState()Fragment在将 a附加到a 后无法调用Activity,如 Android 源代码中第 491 行附近所述。

setInitialSavedState()旨在在代码中实例化片段后立即使用。例如:

AudioContainerFragmentClass newFrag = new AudioContainerFragmentClass();
newFrag.setInitialSavedstate(savedStateObject);
于 2014-01-30T23:47:59.210 回答