How to get text color of TextView?

Android

Android Problem Overview


In given code lbl[0].getTextColor() is giving Error but i don't know how to get text color of textview in java file please help me.

public void angry(View v)
{
	if (lbl[0].getTextColor() == Color.BLACK)
		lbl[0].setTextColor(Color.RED);
	if (lbl[0].getTextColor() == Color.RED)
		lbl[0].setTextColor(Color.BLACK);
}   

Thanks.

Android Solutions


Solution 1 - Android

Use this

textView.getCurrentTextColor()

Solution 2 - Android

There is one important thing to remember: getCurrentTextColor() as well as similar methods like getCurrentHintTextColor() and getHighlightColor() return int value not hex mainly used to define colors. That could even be more confusing as this is negative number, for instance for red it is -65536, for green -16711936 and for white -1.

To make it simple this is because getCurrentTextColor() returns the difference between current color and white color value (both in decimal) minus 1. The expression is: CurrentColor-(WhiteColor+1), where white is 16777215. Of course for standard colors you could use predefined constants like Color.GREEN or Color.MAGENTA, but knowing that you could use effectively getCurrentTextColor() for any colors.

You could read even more about setting and getting colors in Android at http://android4beginners.com/2013/07/lesson-1-3-how-to-change-a-color-of-text-and-background-in-textview/

Solution 3 - Android

You can get the color code from a TextView.

int color=tv.getCurrentTextColor();
String hexColor = String.format("#%06X", (0xFFFFFF & color));

Solution 4 - Android

If you are using the contextcompat library to set the color for new versions of android, you may get a sightly different value then what was above. This test worked for me where I was using the following to set the test color

view.setTextColor(ContextCompat.getColor(ctx, color));

    textColor =view.getCurrentTextColor();
    CoreApp.debug("viewutils", "green color: "+textColor);
    assertThat(textColor, is(ContextCompat.getColor(mCtx, R.color.green)));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJignesh AnsodariyaView Question on Stackoverflow
Solution 1 - AndroidJeffGView Answer on Stackoverflow
Solution 2 - AndroidAndroid4BeginnersView Answer on Stackoverflow
Solution 3 - AndroidRushi AyyappaView Answer on Stackoverflow
Solution 4 - AndroidWayneView Answer on Stackoverflow