Asked 2 years ago
15 Sep 2021
Views 10846
Lesly

Lesly posted

How to set background color of TextView programmatically in android ?

need to change the color of TextView in Activity or Fragment with code not by XML change


<TextView
        android:id="@+id/add"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Add"


/>


i am a beginner at android code so please help me change the background color of TextView programmatically in android
debugger

debugger
answered Sep 15 '21 00:00

hope that you know how to get the TextView object from the identifier


addText=view.findViewById(R.id.add);
addText.setBackgroundColor(Color.parseColor("#808080"));



as above you can see, you can use setBackgroundColor() , which is used to Sets the background color for this view.

but you cant pass a direct color code or color name to setBackgroundColor() .
setBackgroundColor() have parameter which is ColorInt , you can get ColorInt from the Color class .
in short Color.parseColor() used to convert color code or color name to ColorInt which is passed to setBackgroundColor method.
so we used
setBackgroundColor(Color.parseColor("#808080")); // will set grey color

steave ray

steave ray
answered Sep 15 '21 00:00

for setBackgroundColor(), you can generate the ColorInt in many way :

1 . Use direct color name from getResources().getColor()
textview.setBackgroundColor(getResources().getColor(R.color.color_black));

R.color.color_black is the constant for the black color

you can define the color constant at color.xml like this
color.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    
    <color name="color_black">#000000</color>

</resources>



2. user RGB color parameter to define the color
Color.rgb() is get used to convert RGB color parameter to ColorInt

textview.setBackgroundColor(Color.rgb(0, 0, 0));


3. direct use Color class's variable to get ColorInt

textview.setBackgroundColor(Color.BLACK)
Color class have predefined color code which you can use direct , which is following

 
    @ColorInt public static final int BLACK       = 0xFF000000;
    @ColorInt public static final int DKGRAY      = 0xFF444444;
    @ColorInt public static final int GRAY        = 0xFF888888;
    @ColorInt public static final int LTGRAY      = 0xFFCCCCCC;
    @ColorInt public static final int WHITE       = 0xFFFFFFFF;
    @ColorInt public static final int RED         = 0xFFFF0000;
    @ColorInt public static final int GREEN       = 0xFF00FF00;
    @ColorInt public static final int BLUE        = 0xFF0000FF;
    @ColorInt public static final int YELLOW      = 0xFFFFFF00;
    @ColorInt public static final int CYAN        = 0xFF00FFFF;
    @ColorInt public static final int MAGENTA     = 0xFFFF00FF;
    @ColorInt public static final int TRANSPARENT = 0;



4. Use parseColor method from Color which is used color hex code to ColorInt

textview.setBackgroundColor(Color.parseColor("#808080"));

Post Answer