setBackground、setBackgroundDrawable、setBackgroundResource、setBackgroundColor的区别

2,975 阅读1分钟

在 Android 开发中,我们常常遇到对 View 组件的背景颜色或者背景图片进行一些动态的设置。那么常见的这四种方法往往分不清楚,下面我们来看下它们之间的不同之处。

    1. setBackground(Drawable background) 方法的参数是一个Drawable对象.该方法用于设置view组件的背景图片。其中 Drawable 对象可以这样获取:
Drawable background = getResources().getDrawable(R.drawable.xxx); 
    1. setBackgroundDrawable(Drawable background) 方法跟setBackground大体相同。
    1. setBackgroundResource(int resId) 方法的参数是一个组件的id值。该方法也是用于加载组件的背景图片的。
    1. setBackgroundColor(Color.XXX) 方法参数为一个 Color 类的静态常量,它是用来设置背景颜色的方法。

我们在动态设置背景颜色或图片时,有可能该背景颜色有圆角,如果我们直接设置背景颜色,那么原先的圆角就会没有了。所以,如果背景颜色有圆角的话,就不能直接设置了。我们使用如下的方法解决。

 Drawable drawable = tv.getBackground();
if (null != drawable && drawable instanceof GradientDrawable) {
    // 这种情况是设置了带shape的背景颜色
    ((GradientDrawable)drawable).setColor(Color.GREEN);
}





About Me