Android:如何在自定义视图中更改文本颜色?

时间:2015-09-18 12:56:43

标签: android android-layout

我有一个名为ButtonMultiline的视图:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:gravity="center">

<TextView
    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    style="@style/ButtonMultilineCatalogTitle"
    android:text="title"/>

<TextView
    android:id="@+id/subtitle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    style="@style/ButtonMultilineCatalogSubtitle"
    android:text="subtitle"/>

我在此布局上应用背景以在按下时更改颜色:

<selector android:exitFadeDuration="200"
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:drawable="@drawable/btn_large_normal" />
<item android:state_pressed="true">
    <color android:color="@color/background_black_top" />
</item>
<item android:state_focused="true" android:drawable="@drawable/btn_large_pressed" />
<item android:drawable="@drawable/btn_large_pressed" android:state_hovered="true" />
<item android:state_checked="true" android:drawable="@drawable/btn_large_normal" />
<item android:drawable="@drawable/btn_large_normal" />

一切正常,直到这里。

我也想在印刷机上更改两种TextView颜色,但是当我在TextView中添加此行时,此 button_text_catalog.xml 上的膨胀问题出现了崩溃:

<android:background="@drawable/button_text_catalog">

我的 button_text_catalog.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/white" android:state_pressed="true" />
<item android:color="@color/white" android:state_focused="true" />
<item android:color="@color/theme_primary"/>

谢谢你们!

1 个答案:

答案 0 :(得分:2)

使用此代码:

button_text_catalog.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- pressed -->
    <item android:state_pressed="true" android:color="@color/white"/>
    <!-- focused -->
    <item android:state_focused="true" android:color="@color/white"/>
    <!-- activated -->
    <item android:state_activated="true" android:color="@color/white"/>
    <!-- checked -->
    <item android:state_checked="true" android:color="@color/white"/>

    <!-- default -->
    <item android:color="@color/theme_primary"/>

</selector>
Style.xml中的

添加<item name="android:textColor">@drawable/button_text_catalog</item>