How to get text color of TextView?
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.
Use this
textView.getCurrentTextColor()
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/
You can get the color code from a TextView.
int color=tv.getCurrentTextColor();
String hexColor = String.format("#%06X", (0xFFFFFF & color));
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)));
精彩评论