Janusz
Janusz

Reputation: 189494

How to change textColor on press Even in Android?

Is it possible to change the text color of a textview if the textview is pressed? I want to achieve a flashing effect with the color change only lasting as long as the button is pressed.

I know how to change the background of the textview with a selector list and the correct state but how can I change the color of text if the user pushes a button or a simple textview?

Upvotes: 2

Views: 3602

Answers (5)

Ricardo
Ricardo

Reputation: 8291

Taken from official documentation:

XML file saved at res/color/button_text.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
      android:color="#ffff0000"/> <!-- pressed -->
<item android:state_focused="true"
      android:color="#ff0000ff"/> <!-- focused -->
<item android:color="#ff000000"/> <!-- default -->
</selector>

This layout XML will apply the color list to a View:

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/button_text"
android:textColor="@color/button_text" />

Upvotes: 3

Janusz
Janusz

Reputation: 189494

You can define a selector for colors as well. A short example that only distinguishes between pressed and all other states is:

<?xml version="1.0" encoding="utf-8"?>
<selector
   xmlns:android="http://schemas.android.com/apk/res/android">
   <item
      android:state_pressed="true"
      android:color="#FFFFFF" />
   <item
      android:color="#4C566C" />
</selector>

For a full documentation on the selector see this unofficial documentation.

Put every color selector in a single file and put this files in a directory called color in the resources folder of your project.

Upvotes: 7

Ryan Conrad
Ryan Conrad

Reputation: 6900

you can change it using the setTextColor(ColorStateList) method

myTextView.setTextColor(myColorStates);

Upvotes: 1

weakwire
weakwire

Reputation: 9300

search for color selector to use in the

android:setTexColor

attr

Upvotes: 1

JeremyFromEarth
JeremyFromEarth

Reputation: 14344

myTextView.setTextColor( 0xFFFF0000 )

Upvotes: 0

Related Questions