我有一个自定义视图,假设这是它的代码:
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);
}
}
很简单。我的自定义视图从 XML 读取属性并应用它们。这些属性在配置更改时保存和恢复。
但是如果我有两种不同的布局,例如两个不同的方向:
[layout-port/view.xml]
<CustomView
custom:visible="true"
custom:enabled="true"
[layout-land/view.xml]
<CustomView
custom:visible="false"
custom:enabled="false"
我的问题是,当更改设备方向时,视图状态被保存为可见并启用,但现在 XML 布局状态视图也不应该有。构造函数在 onRestoreInstanceState 之前被调用,并且 XML 属性被保存的状态覆盖。我不希望这样,XML 优先于保存的状态。
我做错了什么?解决这个问题的最佳方法是什么?