简体   繁体   中英

Changing the textColor when the state changes in TextView in Android

Hey I am trying to change the textColor in TextView when the user press it. I am trying to make something like hyperlink button in Windows 8 . I have this selector in res/color folder .

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_hovered="true">
        <color android:color="@color/darkBlue"/>
    </item>
    <item  android:state_pressed="true">
        <color android:color="@color/lightBlue"/>
    </item>
    <item android:color="@color/black"/> <!-- default color -->
</selector>

and I use it like this

<TextView
        android:id="@+id/tw_language"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/language_label"
        android:layout_marginRight="3dp"
        android:clickable="true"
        android:autoLink="all"
        android:text="@string/default_language_label"
        android:textColor="@color/language_button"

        />

In activity when I get the reference to this textView I set mLanguage.setPaintFlags(mLanguage.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

to get underlined text. And the app crashes using this. If I set

android:background="@color/language_button"

Instead of textColor it works fine. Does anyone know what I am doing wrong?

You need to add attribute to your TextView like below

<TextView
    android:id="@+id/txtResult"
    style="@drawable/language_button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
/>

style="@drawable/language_button" is your selector file. I have defined that file in drawable/stack.xml directory.

You can do this:

textView = (TextView)findViewById(R.id.myTextView);
    mMainView.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            textView.setTextColor(Color.GREEN);//set the color here
        }

    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM