setBackgroundColor的使用方法源码
时间: 2024-05-07 16:21:31 浏览: 5
setBackgroundColor是Android中View类的一个方法,用于设置View的背景颜色。其使用方法如下:
Java代码:
```
view.setBackgroundColor(color);
```
其中,view是要设置背景颜色的View对象,color是要设置的颜色值,可以是一个Color对象或者是一个颜色的整型值。
以下是setBackgroundColor方法的源码:
```
public void setBackgroundColor(@ColorInt int color) {
final Drawable bg = getBackground();
if (bg instanceof ColorDrawable) {
((ColorDrawable) bg.mutate()).setColor(color);
computeOpaqueFlags();
invalidate();
} else {
setBackground(new ColorDrawable(color));
}
}
```
其中,@ColorInt是一个注解,用于标识参数是颜色值,而非整型值。该方法首先通过getBackground方法获取View的背景Drawable对象,如果该对象是一个ColorDrawable,则直接修改其颜色值;否则,先将原来的背景Drawable替换为一个新的ColorDrawable对象,再设置其颜色值。最后,通过invalidate方法使View的显示内容无效,需要重新绘制。