我想为一个应用程序添加多个主题,并且可以通过编程方式进行选择。
如何在这些主题内为特定视图定义样式?
假设我有一个ImageView在以下位置显示徽标my_layout.xml
:
<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>
如何更改src
更改主题的ImageView的?
有没有一种方法可以为主题定义自定义元素,以便随后将其应用于特定视图?
就像是:
<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"
...
上面的例子没有用;我遗漏了一些东西,或者无法实现该结果?
提前致谢。
我根据以下答案自己找到了解决方案:
声明属性以用作样式参考:
<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的样式将根据所应用的主题进行更改。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句