通常selector都是在drawable/color文件夹中定义好,但有时候一些特殊需求需要我们动态通过代码去更改,这个时候就要用到StateListDrawable 和 ColorStateList 了,分别是设置图片和颜色的类

今天先讲通过代码实现ColorStateList,代码呈现如下:

private static ColorStateList createColorStateList(Context context, int color) {

int[] colors = new int[]{ContextCompat.getColor(context, color), ContextCompat.getColor(context, R.color.gray)};

int[][] states = new int[2][];

states[0] = new int[]{android.R.attr.state_checked};

states[1] = new int[]{-android.R.attr.state_checked};

ColorStateList colorList = new ColorStateList(states, colors);

return colorList;

}

其中:-android.R.attr.state_checked 和 android.R.attr.state_checked 的区别在于 “-” 号代表值里的true 和 false ,有“-”为false 没有则为true

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐