【发布时间】:2015-05-15 12:21:32
【问题描述】:
我正在尝试根据父 Theme 在我的视图中包含不同的布局。
遵循这个想法:
attrs.xml
<attr name="themeLayout" format="reference" />
styles.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>
activity.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:我将MainActivity的Theme设置为android:theme="@style/AppTheme"
注意 #2: 在布局编辑器的设计视图中,一切都按预期工作。如果我切换主题,则包含会正确更新。
另请参阅以下屏幕截图:
【问题讨论】:
-
从来没有想过这样做......希望有人回答,因为这是你发现的一个很酷的问题
-
这种方式你不能包含基于主题的布局可能必须创建和加载主题基础布局。
-
@HareshChhelana 我不确定你想说什么。它认为奇怪的部分是布局编辑器可以解析属性,但运行时的代码也不能这样做。
标签: android android-layout android-styles android-attributes