使用Selector改變TextView的字體顏色textColor的方法


先上Selector文件,名字為singer_fragment_top_text_style.xml,

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/colorPrimaryDark" android:state_selected="true" />
    <item android:color="@color/colorAccent" android:state_selected="false" />
</selector>

有人可能會發現這個selector文件和我們平時在Drawable里面看到的不一樣,因為在drawable文件夾中的selector,是不能有android:color屬性的,這個文件其實是放在res/color文件夾中的;

應用的時候,只需要對TextView的textColor直接賦值就好了,如下:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/singer_choice_tv"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_marginLeft="12dp"
    android:layout_marginRight="12dp"
    android:background="@drawable/singer_fragment_top_style"
    android:gravity="center"
    android:minWidth="40dp"
    android:text="A" android:textColor="@color/singer_fragment_top_text_style"
    android:textSize="18sp" />

注意,對android:textColor賦值時,不是@drawable/xxxxx,而是@color/XXXXX


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM