定义特定的视图样式以在主题内使用 [英] Define specific view style to use inside theme
问题描述
我想为一个应用添加多个主题,并且可以通过编程方式进行选择.
I'd like to add more than one theme for an app, selectable programmatically.
如何在这些主题中为特定视图定义样式?
How can I define a style for a specific view inside those themes?
假设我有一个ImageView,它在my_layout.xml
中显示徽标:
Let's say I have an ImageView that show a logo in 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>
如何更改ImageView的src
来更改主题?
How can I change the src
of the ImageView changing the Theme?
是否可以为主题定义自定义元素,以便随后将其应用于特定视图?
Is there a way to define custom elements for a theme so that I can then apply to a specific view?
类似的东西:
<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"
...
上面的例子没有用;我遗漏了一些东西,还是无法达到那个结果?
The above example didn't work; I'm missing something or it isn't possible to achieve that result?
谢谢.
推荐答案
我自己根据声明用作样式引用的属性:
Declare attribute to use as style reference:
<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>
定义引用不同样式的主题:
Define themes that refer to different styles:
<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的样式根据所应用的主题而改变.
Now the style applied to the ListView changes according to the theme applied.
这篇关于定义特定的视图样式以在主题内使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!