我目前面临一个非常具体的挑战。 事情是这样的:
我构建了一个自定义 View ,我想在其中设置来自 xml 布局的特定属性。 我在 View 的构造函数中获取自定义属性。 现在在方向改变之后,这个构造函数不再被调用,但我为我的自定义属性设置了不同的值。 有什么方法可以自动获取这些新值,还是我必须在方向改变时手动设置它们(或再次膨胀)?
自定义 View :
public MyCustomView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.MyCustomView,
0, 0);
try {
mAttr = a.getBoolean(R.styleable.MyCustomView_customAttr, false);
} finally {
a.recycle();
}
}
布局横向
<com.me.MyCustomView
custom:customAttr="false" />
布局纵向
<com.me.MyCustomView
custom:customAttr="true" />
谢谢你的建议!
最佳答案
您是否在 list 中的 Activity 上使用了 android:configChanges="orientation"
?
像这样:
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name">
如果你这样做,你就是在请求自己管理方向变化,所以你有责任根据需要重新创建 View (重新膨胀它,是的)。您可以在 Activity 的 onConfigurationChanged()
调用中执行此操作。
但如果您删除此设置,默认情况下应重新创建 Activity ,这样您的布局将使用新属性重新构建...
如本主题中所述:oncreate called on every re-orientation
关于Handling Runtime changes here的更多信息.
关于android - 自定义属性 - 方向变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17673316/