Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 views
in Technique[技术] by (71.8m points)

android - Using selector to change TextView text color

I'm trying to use a TextView to define the style of a TabWidget on a tabhost.

I just created a selector for bgcolor and works fine, but i want to make a selector for textColor but the text color don't change:

This is my tab_text_selector.xml:

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

</selector>

And this is the code when i'm trying to use on a textView:

TextView txtTab=new TextView(this);
        txtTab.setTextColor(R.drawable.tab_text_selector);
        txtTab.setBackgroundResource(R.drawable.tab_bg_selector);
        txtTab.setGravity(Gravity.CENTER);
        txtTab.setText("Agregar Idea");

I know the text color must be white in any case but it doesn't.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

1) Use tab_text_selector.xml as below and put it into res/color folder:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true" android:color="@android:color/white" />
    <item android:state_focused="true" android:color="@android:color/white" />
    <item android:state_pressed="true" android:color="@android:color/white" />
    <item android:color="#504f4f" /> <!-- default case -->
</selector>

And set it to your textview as below..

TextView tv = (TextView) findViewById(R.id.TextView1) ;
tv.setTextColor(context.getResources().getColor(R.color.tab_text_selector));

2) The Second option is If you are using textview in xml rather than using programatically then use tab_text_selector.xml as below :

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:text="TextView"
    android:textColor="@??drawable/tab_text_sel??ector" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...