I have a custom view, let's say this is its code:
public class CustomView extends View {
boolean visible;
boolean enabled;
public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomView, 0, 0);
try {
visible = a.getBoolean(R.styleable.CustomView_visible, true);
enabled = a.getBoolean(R.styleable.CustomView_enabled, true);
} finally {
a.recycle();
}
// Apply XML attributes here
}
@Override
public Parcelable onSaveInstanceState() {
// Save instance state
Bundle bundle = new Bundle();
bundle.putParcelable("superState", super.onSaveInstanceState());
bundle.putBoolean("visible", visible);
bundle.putBoolean("enabled", enabled);
return bundle;
}
@Override
public void onRestoreInstanceState(Parcelable state) {
// Restore instance state
// This is called after constructor
if (state instanceof Bundle) {
Bundle bundle = (Bundle) state;
visible = bundle.getBoolean("visible");
enabled = bundle.getBoolean("enabled");
state = bundle.getParcelable("superState");
}
super.onRestoreInstanceState(state);
}
}
Pretty straightforward. My custom view reads attributes from XML and applies them. These attributes are saved and restored on configuration changes.
But if I have two different layout, for example for two different orientations:
[layout-port/view.xml]
<CustomView
custom:visible="true"
custom:enabled="true"
[layout-land/view.xml]
<CustomView
custom:visible="false"
custom:enabled="false"
My problem is that when changing the device orientation, view state is saved as visible and enabled, but now XML layout states the view shouldn't have either. Constructor gets called before onRestoreInstanceState and the XML attributes are getting overwritten by the saved state. I don't want that, XML has priority over saved state.
I am doing something wrong? What would be the best way to solve this ?