仅将样式应用于特定TextView

时间:2014-05-14 13:52:41

标签: android xml

我有两个主题,我在Android应用程序之间来回切换。在某些地方,我有TextView s我想保持默认颜色。在其他地方,我希望它们是另一种颜色(让我们说是橙色)。更改主题时,我只想 之前为橙色的TextView变为蓝色。

有没有办法在Android中执行此操作?我有一些想法,比如html / css中的类标记,但似乎找不到任何东西。

编辑:用html / css等价物澄清我的意思:

<div>This text is black</div>
<div class="redDiv">This text is red</div>

.redDiv {
    color:red;
}

1 个答案:

答案 0 :(得分:6)

假设您的申请中有两个主题:MyFirstThemeMySecondTheme

<style name="MyFirstTheme" parent="android:Theme">
    <item name="android:textViewStyle">@style/MyFirstTheme.TextView</item>
    [...]
</style>
<style name="MySecondTheme" parent="android:Theme">
    <item name="android:textViewStyle">@style/MySecondTheme.TextView</item>
    [...]
</style>

styles.xml 中定义的textview样式可能如下所示:

<style name="MyFirstTheme.TextView" parent="@android:style/Widget.TextView">
    <item name="android:textColor">@android:color/black</item>
    [...]
</style>
<style name="MySecondTheme.TextView" parent="@android:style/Widget.TextView">
    <item name="android:textColor">@color/orange</item>
    [...]
</style>
<style name="PersistentTheme.TextView" parent="@style/MyFirstTheme.TextView">
    <item name="android:textColor">@color/red</item>
</style>

因此,当您拥有包含两个TextView的布局时,您可以通过不设置任何额外内容来完全跟随活动主题,并且可以通过指定style将其他外观应用于其他TextView实例属性:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

    <!-- This textview will change text color when other style applied -->
    <TextView
        android:id="@+id/tv_styledependent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <!-- This textview will always have the same (red) text color -->
    <TextView
        android:id="@+id/tv_persistent"
        style="@style/PersistentTheme.TextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv_styledependent" />

</RelativeLayout>