我想为应用添加多个主题,可以通过编程方式进行选择。
如何为这些主题中的特定视图定义样式?
假设我有一个在my_layout.xml
中显示徽标的ImageView:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<ImageView
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="@drawable/ic_logo"
android:contentDescription="@string/app_name"
/>
<!-- ...other views... -->
</RelativeLayout>
如何更改ImageView的src
更改主题?
有没有办法为主题定义自定义元素,以便我可以应用于特定视图?
类似的东西:
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="MyTheme" parent="android:Theme.Holo.Light">
<item name="logoImageView">@style/baseLogoImageView</item>
</style>
<style name="baseLogoImageView">
<item name="android:src">@drawable/ic_logo</item>
</style>
</resources>
然后在my_layout.xml
中使用它:
...
<ImageView style="@style/logoImageView"
...
上面的例子不起作用;我错过了什么或者不可能实现这个结果?
提前致谢。
答案 0 :(得分:1)
我自己找到了一个基于this answer的解决方案:
声明要用作样式引用的属性:
<declare-styleable name="CustomThemeViews">
<attr name="myViewStyle" format="reference"/>
</declare-styleable>
为每个主题定义样式:
<style name="myViewStyleTheme01">
<item name="android:background">#f00</item>
</style>
<style name="myViewStyleTheme02">
<item name="android:background">#0f0</item>
</style>
定义引用不同样式的主题:
<style name="AppTheme" parent="android:Theme.Light">
<item name="myViewStyle">@style/myViewStyleTheme01</item>
</style>
<style name="AppThemeAlternative" parent="android:Theme.Light">
<item name="myViewStyle">@style/myViewStyleTheme02</item>
</style>
在布局中使用主题样式
<ListView style="?attr/myViewStyle"
android:layout_width="match_parent"
android:layout_height="match_parent"
...
现在,应用于ListView的样式会根据应用的主题而更改。