最近在做一个使用接口返回的字符串:"#ff0000" 来动态设置drawable背景颜色与动态设置状态选择器selector的需求,之前写习惯了shape的xml,还是第一次写动态的,有点搞笑,搞笑的是自己没写过,不知道会不会写。
1.很简单,直接布局代码:
2.Activity代码如下:
//在Activity的初始化中直接复制下面代码:
RelativeLayout llTitle = findViewById(R.id.ll_title);
llTitle.setBackgroundDrawable(getStateListDrawable());
llTitle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
//在Activity中的方法
public static StateListDrawable getStateListDrawable() {
StateListDrawable selector = new StateListDrawable();
int parseColor = Color.parseColor("#FF00FF");
Drawable pressDrawable = getRoundRectDrawable(20, Color.parseColor("#ff00ff"), true, 0);
Drawable selectDrawable = getRoundRectDrawable(20, Color.parseColor("#00ffff"), true, 0);
Drawable defaultDrawable = getRoundRectDrawable(20, Color.parseColor("#00ffff"), true, 0);
selector.addState(new int[]{android.R.attr.state_pressed}, pressDrawable);
selector.addState(new int[]{android.R.attr.state_selected}, selectDrawable);
// 添加一个默认状态, 默认状态必须写在其他状态的最后面, 否则其他状态失效
selector.addState(new int[]{}, defaultDrawable);
return selector;
}
public static GradientDrawable getRoundRectDrawable(int radius, int color, boolean isFill, int strokeWidth){
//左上、右上、右下、左下的圆角半径
float[] radiusList = {radius, radius, radius, radius, radius, radius, radius, radius};
GradientDrawable drawable = new GradientDrawable();
drawable.setCornerRadii(radiusList);
drawable.setColor(isFill ? color : Color.TRANSPARENT);
drawable.setStroke(isFill ? 0 : strokeWidth, color);
return drawable;
}
//补充设置渐变色
public static GradientDrawable getRoundRectDrawable(int radius, int color, boolean isFill, int strokeWidth){
//左上、右上、右下、左下的圆角半径
float[] radiusList = {radius, radius, radius, radius, radius, radius, radius, radius};
GradientDrawable drawable = new GradientDrawable();
//设置渐变色,渐变方向从左上到右下,渐变颜色设置
GradientDrawable gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.TL_BR,
new int[]{R.color.blue_0B1152, R.color.blue_4E5988});
drawable.setCornerRadii(radiusList);
drawable.setColor(isFill ? color : Color.TRANSPARENT);
drawable.setStroke(isFill ? 0 : strokeWidth, color);
return drawable;
}
亲测有效,写这篇文章只是想记录一下完整的实现代码。
相关博客推荐:
Android状态选择器selector的详细使用汇总
selector的两种设置方式