Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change TextView text color on selection?

My scenario is when user click on a TextView text, it will change it's color black to red. I have tried to solve this problem but nothing happened. Here is my effort: My TextView

 <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:textSize="24sp"
        android:textColor="@color/text_selector"
        android:text="Shamima Sultana Shaumi"/>

and the text_selector class is:

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

Whenever I click on TextView, nothing is happened. I can't figured out what was my problem.

like image 203
androidcodehunter Avatar asked Jan 06 '23 07:01

androidcodehunter


1 Answers

The selector can be e.g. this:

<?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/red" />
    <item android:color="@android:color/black"/>
</selector>

and use this OnClickListener for your textView:

textView.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        boolean isSelectedAfterClick = !v.isSelected();
        v.setSelected(isSelectedAfterClick);

        if (isSelectedAfterClick){
            //do something
        } else {
            //do something
        }
    }
});

Instead of state_selected, isSelected and setSelected you can use (respectively) state_activated, isActivated and setActivated.

like image 85
Bartek Lipinski Avatar answered Feb 07 '23 15:02

Bartek Lipinski