How to change the color of TextView at runtime with shape attribute on Android?

我们两清 提交于 2019-12-04 19:41:58

I found a solution with PaintDrawable which contains color and radius attributes. But It have to set the color in the contructor. So I have to new a PaintDrawable at runtime every time and set it to the background drawable of a TextView.

public static PaintDrawable getRoundedColorDrawable(int color, float radius, int padding) {
    PaintDrawable paintDrawable = new PaintDrawable(color);
    paintDrawable.setCornerRadius(radius);
    paintDrawable.setPadding(padding, padding, padding, padding);
    return paintDrawable;
}

You need to set the background a different shape with the correct Solid element. setBackgroundColor I believe just is a short cut to something like:

void setBackgroundColor(int color){
 ColorDrawable drawable = new ColorDrawable(color);
 setBackgroundDrawable(drawable);
}

So yea you will need a few shapes :)

I had the same problem

You can use this method

TextView tv = // ... //;
tv.setBackgroundResource(R.drawable.myshape);

It works fine for me!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!