I have a custom view, let's say this is its code:
public class CustomView extends View {
boolean visible;
boolean enabled;
public ScheduleView(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();
}
}
@Override
public Parcelable onSaveInstanceState() {
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) {
if (state instanceof Bundle) {
Bundle bundle = (Bundle) state;
visible = bundle.getBoolean("visible");
enabled = bundle.getBoolean("enabled");
state = bundle.getParcelable("superState");
}
super.onRestoreInstanceState(state);
}
}
Pretty simple. My custom view reads attributes from XML and applies them. These attributes are saved and restored when the configuration changes.
But if I have two different layouts, 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 the orientation of the device changes, the view state is saved as visible and enabled, but now the XML layout states that there should not be a view either. The constructor is called before onRestoreInstanceState, and the XML attributes get the rewritten state. I do not want this, XML has priority over saved state.
Am I doing something wrong? What would be the best way to solve this problem?