Togglebutton Change State On Orientation Changed
Solution 1:
If you want your CustomButton to retain its current state after an orientation change simply override onSaveInstanceState() and onRestoreInstanceState().
A Solution
I ran through your code and noticed that toggleBut
's state was being changed after onActivityCreated() but before onStart(). To avoid having any of these methods override your toggle settings, I simply moved these lines from onViewCreated():
booleansaved= loadPreferences("toggleBut");
toggleBut.setChecked(saved);
and put them in onResume(). Hope that helps!
Better Solution
Your ToggleButton setting are being overwritten when the system tries to restore the default saveInstanceState
, probably in Fragment.onActivityCreated().
In CustomButton, override these functions like so:
@Overrideprotected Parcelable onSaveInstanceState() {
Bundlestate=newBundle();
state.putParcelable("default", super.onSaveInstanceState());
state.putParcelable("toggle", toggleOnOffButton.onSaveInstanceState());
return state;
}
@OverrideprotectedvoidonRestoreInstanceState(Parcelable state) {
Bundlebundle= (Bundle) state;
super.onRestoreInstanceState(bundle.getParcelable("default"));
toggleOnOffButton.onRestoreInstanceState(bundle.getParcelable("toggle"));
};
Understand that the system will still change the ToggleButton states, without the one more thing. But let me try to explain what;s happening:
onActivityCreated(Bundle savedInstanceState)
passes it'ssavedInstanceState
to every layout element by calling 'onRestoreInstanceState(Bundle savedInstanceState)`.- onRestoreInstanceState() begins with the layout's root element first and traverses up the layout's hierarchy (in this case it sets the checked state of each ToggleButton last).
- Since the default methods are clearly not working, we need to define our own save / restore method for the ToggleButtons. Otherwise any changes we make before the system calls onRestoreInstanceState() will be changed again by the system...
So, lastly we will exclude the ToggleButtons from this default behavior by adding the following line to CustomButton.onFinishInflate():
toggleOnOffButton.setSaveEnabled(false);
Voila, your CustomButtons automatically retain their state.
Post a Comment for "Togglebutton Change State On Orientation Changed"