如何在xml中的样式中将文本颜色更改为特定的textView?

时间:2018-02-01 22:19:19

标签: android xml layout colors

在android studio xml文件样式中,我想更改特定textView的颜色,但不知道如何引用它。我能找到的只是

<item name="android:textColor">@color/colorRed</item>

这会将颜色更改为所有 textViews,但我需要它来定位特定的文本。 Haven没有通过谷歌搜索找到任何东西。看起来像一个简单的事情,似乎无法找到解决方案......任何想法?它必须在xml而不是java代码中完成。

更新: 更清楚一点:我有三个样式的textViews,我希望它们都有不同的颜色。如果我使用上面的代码,所有textViews都会改变。如何为样式中的每个textView设置一种颜色?

1 个答案:

答案 0 :(得分:1)

您可以通过设置样式直接在xml中为TextView执行此操作。它看起来像这样:

<TextView
  android:id="@+id/text_view_id_one"
  android:layout_height="wrap_content"
  android:layout_width="wrap_content"
  android:text="@string/hello_one"
  style="@style/ColorOne"/>

<TextView
  android:id="@+id/text_view_id_two"
  android:layout_height="wrap_content"
  android:layout_width="wrap_content"
  android:text="@string/hello_two"
  style="@style/ColorTwo"/>

<TextView
  android:id="@+id/text_view_id_three"
  android:layout_height="wrap_content"
  android:layout_width="wrap_content"
  android:text="@string/hello_three"
  style="@style/ColorThree"/>

然后在您的样式文件中,您可以创建三种不同的样式:

<style name="ColorOne" parent="AppTheme">
    <item name="android:textColor">@color/color_one</item>
</style>

<style name="ColorTwo" parent="AppTheme">
    <item name="android:textColor">@color/color_two</item>
</style>

<style name="ColorThree" parent="AppTheme">
    <item name="android:textColor">@color/color_three</item>
</style>