Search code examples
androidcolorscontrast

How to control the contrast of text?


How do you change the color contrast of text when the background changes? for example If I was to have a black background, black text would not be visible.


Solution

  • This might be helpful: http://developer.android.com/guide/topics/resources/color-list-resource.html

    It is a way you can set a color that will change based on certain circumstances.

    For example, say you have a TextView that you want to have white text while it is enabled and black text when it is disabled. You can set that up in a xml file using the references in the link above, and then in your xml layout where you define the TextView set the android:textColor to @color/my_text_color. (my_text_color being the xml color list file you created)

    Then, as the TextView changes from enabled to disabled (or whatever you end up setting up in the xml file) the color will change automatically as well.

    That's one way to do it. However, you might want to try to clarify what you are looking for as it isn't perfectly clear in your question.

    Update

    After Matt's comment, here is a method you could use to get an inverted color value. There is probably a better way but this should work.

    private int getInverseColor(int color){
        int red = Color.red(color);
        int green = Color.green(color);
        int blue = Color.blue(color);
        int alpha = Color.alpha(color);
        return Color.argb(alpha, 255-red, 255-green, 255-blue);
    }
    

    You could programmaticly get the color int from a view such as a TextView using one of the getTextColor() methods. You may have to tinker with a Color State List like I linked to above to get the color you want. Then pass that color to the method above to get the inverted color int and set it with one of the setTextColor() methods.