How to change the text color on a TextView by clicking it?

First of all, I declared my values j, u as integers because text.getCurrentTextColor() and text.setTextColor() take only integers.
Then I created an OnClickListener() method, so that when I click it, it runs the code inside the method.
After that I created two if conditions that will continuously switch the text color either to color id "j" or color id "u".

I ran the program on my device and when I clicked it, the text just disappeared and never came back again.

Im new to programming, and I can't find the answer to my problem in any posts.

Did I understand the OnClickListener() event correctly?
And is android:clickable="true" necessary?

<TextView
        android:id="@+id/yourlabel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="LabelText"
        android:textSize="20dp"
        android:clickable="true" />

Java

        final int j=100000; //Color id number
        final int u=690856; //Color id number
        text=(TextView)findViewById(R.id.yourlabel);
        text.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                       if(j==text.getCurrentTextColor())
                       {
                           text.setTextColor(u);
                       }
                        else
                       {
                           text.setTextColor(j);
                       }

                    }

                }
        );

Upvotes: 0

Views: 124

Answers (2)

arnoduebel
arnoduebel

Reputation: 349

You understood the onClickListener correctly and no, you do not have to use android:clickable="true" in this case. The problem you are facing is that getCurrentTextColor() returns other values than you are expecting. A detailed answer can be found here: getCurrentTextColor from a TextView returns a weird color

To fix your code you should declare your colors in colors.xml like this:

<color name="yourFirstColor">#0097A7</color>
<color name="yourSecondColor">#536DFE</color>

In your Activity you can get the colors via:

final int j = ContextCompat.getColor(getApplicationContext(), R.color.yourFirstColor);
final int u = ContextCompat.getColor(getApplicationContext(), R.color.yourSecondColor);

Upvotes: 1

user6363583
user6363583

Reputation: 104

Use handler to change. Try something like this...

Handle handler;

Then on your onCreate initialize it

handler = new Handler();

And for a flexible solution I am creating a method

private void changeTextColor(TextView tv, int color){
handler.post(new Runnable(){
@Override
private void run(){
text.setTextColor(color);
}
});
}

This should work...

Upvotes: 0

Related Questions