我正在尝试创建一个片段,在它显示回来之后保留其状态. 为此,我尝试在onPause()中使用getFragmentManager().saveFragmentInstanceState().然后在onCreateView()中调用setInitialSavedState(). 我面临的问题是我不
为此,我尝试在onPause()&中使用getFragmentManager().saveFragmentInstanceState().然后在onCreateView()中调用setInitialSavedState().
我面临的问题是我不知道如何准确地使用它们以及何时调用它们.
这两个函数都采用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 */); } }只是自己调查一下,并认为我会记录我发现的东西.
在将片段附加到活动后,无法调用setInitialSavedState(),如Android源代码around line 491中所述.
setInitialSavedState()旨在在代码中实例化片段后立即使用.例如:
AudioContainerFragmentClass newFrag = new AudioContainerFragmentClass(); newFrag.setInitialSavedstate(savedStateObject);