androidtextviewbackground-drawable

How to change TextView's background color dynamically?


I have reffered this question and implemented circular background for TextView using circle.xml (in res/drawable) and setting it as android:background="@drawable/circle" for TextView. But what I need is , I need to set the background color dynamically through code. Just like the lollipop contacts app as shown below

enter image description here

How can I acheive this? I need the TextView background in circular shape always as shown in above image


Solution

  • You can change TextView background color in many ways like:

    textView.setBackgroundColor(Color.parseColor("#f44336"));
    

    or

    textView.setBackgroundColor(Color.RED);
    

    or

    textView.setBackgroundColor(Color.rgb(255, 0, 0));
    

    or

    textView.setBackgroundColor(getColor(R.color.red_color));
    

    and many other ways too...

    Edit:

    If you want to change your TextView background color that was defined in your drawable file, do it like this:

    GradientDrawable:

    GradientDrawable tvBackground = (GradientDrawable) textView.getBackground();
    tvBackground.setColor(Color.parseColor("#f44336"));
    

    StateListDrawable:

    StateListDrawable tvBackground = (StateListDrawable) textView.getBackground();
    tvBackground.setColorFilter(Color.parseColor("#f44336"), PorterDuff.Mode.SRC_ATOP);
    

    But if you don't want to set a color filter, you can get the drawable of each state separately by following the answer in this link.