android:tint很好用,既方便又节省APK大小。 但是遇到selector这种方式的时候有点麻烦,必须以写代码的方式. 这种方式务必知道两点: 1. 以下三者之间是一一对应的。 int[] colors = new int[]{ ContextCompat.getColor(context, R.color.disable), //1 ContextCompat.getColor(context, R.color.icon_normal_color), //2 ContextCompat.getColor(context, R.color.disable)};//3 states[0] = new int[]{android.R.attr.state_pressed};//1 states[1] = new int[]{android.R.attr.state_enabled};//2 states[2] = new int[]{};//3 stateListDrawable.addState(states[0], drawable); //1 stateListDrawable.addState(states[1], drawable);//2 stateListDrawable.addState(states[2], drawable);//3 2. 在states[0] = new int[]{android.R.attr.state_pressed}中如果要取反值,那么加“-”负号。 也就是states[0] = new int[]{-android.R.attr.state_pressed}.这点很关键。 public Drawable getOptionsTintDrawable(Context context, int resId) { Drawable drawable = ContextCompat.getDrawable(context, resId); int[] colors = new int[]{ContextCompat.getColor(context, R.color.disable), ContextCompat.getColor(context, R.color.icon_normal_color), ContextCompat.getColor(context, R.color.disable)}; int[][] states = new int[3][]; states[0] = new int[]{android.R.attr.state_pressed}; states[1] = new int[]{android.R.attr.state_enabled}; states[2] = new int[]{}; ColorStateList colorList = new ColorStateList(states, colors); StateListDrawable stateListDrawable = new StateListDrawable(); stateListDrawable.addState(states[0], drawable); stateListDrawable.addState(states[1], drawable); stateListDrawable.addState(states[2], drawable); Drawable.ConstantState state = stateListDrawable.getConstantState(); drawable = DrawableCompat.wrap(state == null ? stateListDrawable : state.newDrawable()).mutate(); DrawableCompat.setTintList(drawable, colorList); return drawable; }
android ColorStateList和StateListDrawable的使用特点
最新推荐文章于 2024-05-24 17:26:29 发布