我试图根据 parent 在我的 View 中包含不同的布局Theme
。
按照思路:
attrs.xml
<attr name="themeLayout" format="reference" />
样式.xml
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="themeLayout">@layout/layout_a</item>
</style>
<style name="AppThemeSecond" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="themeLayout">@layout/layout_b</item>
</style>
活动.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<include layout="?attr/themeLayout" />
</RelativeLayout>
当我运行上面的代码时,我会得到以下异常:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.my.package/com.my.package.MainActivity}: android.view.InflateException: You must specifiy a valid layout reference. The layout ID ?attr/themeLayout is not valid.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: android.view.InflateException: You must specifiy a valid layout reference. The layout ID ?attr/themeLayout is not valid.
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:866)
我究竟做错了什么?有可能做到这一点吗?
注意#1:我将我的Theme
设置MainActivity
为android:theme="@style/AppTheme"
注意#2:在布局编辑器的设计视图中,一切都按预期工作。如果我切换主题,则包含会正确更新。
另请参阅以下屏幕截图: