Changing TextView background color on click android

Apart from the above answers,try this code snippet too.

 <selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true">
      <shape>
        <gradient android:endColor="#AD1F2D" android:startColor="#AD1F2D" />
      </shape>
    </item>
    <item android:state_focused="true">
      <shape>
        <gradient android:endColor="#ff4b46" android:startColor="#ff4b46" />
      </shape>
    </item>
    <item>
      <shape>
        <gradient android:endColor="#ff4b46" android:startColor="#ff4b46" />
      </shape>
    </item>

</selector>

I hope this will useful for everyone.


If the textview is clicked the background changes to yellow and remains yellow until it is click again. Then it returns to its default background.

It's a matter of logic as you need to keep in your click listener the current click state.(blind coding):

textView.setOnClickClickListener(new View.OnClickListener() {
    private boolean stateChanged;
    public void onClick(View view) {
        if(stateChanged) {
            // reset background to default;
            textView.setBackgroundDrawable(circleOffDrawable);
        } else {
            textView.setBackgroundDrawable(circleOnDrawable);
        }
        stateChanged = !stateChanged;
    }
});

To improve the answer, you should keep stateChanged flag in the activity and retain its value across activity recreations - if the user rotates the activity. (Store the flag in onSaveInstanceState and restore in onCreate if its parameter is not null.)