我们自定义View的时候有时会用到background,为了调用者更好的使用,我们可以复用Android自带的background属性,而不是自定义属性.
获取并修改background的内容如下(以自定义TextView为例):
paint = new Paint();
paint.setAntiAlias(true);
Drawable background = getBackground();
//background包括color和Drawable,这里分开取值
if (background instanceof ColorDrawable) {
ColorDrawable colordDrawable = (ColorDrawable) background;
int color = colordDrawable.getColor();
paint.setColor(color);
setBackgroundDrawable(null);
} else {
bgBitmap = ((BitmapDrawable) background).getBitmap();
setBackgroundDrawable(null);
}
paint.setStyle(Paint.Style.FILL);
分别拿到里面的color或者Drawable之后就可以根据自己需求对背景进行修改.