I'm trying to create a Fragment
that retains its state after it is shown back.
For this I tried using getFragmentManager().saveFragmentInstanceState()
inside onPause()
& then calling setInitialSavedState()
inside onCreateView()
.
Issues I'm facing is I dont know how to use them exactly and when to call them.
Also both functions take a paramater of type SavedState
, which I'm not sure how to use.
Code:
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 */);
}
}
Just investigating this myself and thought I'd record what I found.
setInitialSavedState()
can't be called after a Fragment
has been attached to an Activity
, as noted in the Android source code around line 491.
setInitialSavedState()
is intended to be used immediately after instantiating fragments in code. For example:
AudioContainerFragmentClass newFrag = new AudioContainerFragmentClass();
newFrag.setInitialSavedstate(savedStateObject);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With