一般我们在xml中设置selector来显示某个View的背景颜色为点击和非点击状态,但有时候需要在代码中动态设置,可以使用StateListDrawable来实现:
StateListDrawable stateListDrawable = new StateListDrawable();
int corner = context.getResources().getDimensionPixelSize(R.dimen.corner);
GradientDrawable gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT, new int[]{startColor, endColor});
gradientDrawable.setCornerRadius(corner);
stateListDrawable.addState(new int[]{-android.R.attr.state_pressed}, drawable);
gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT, new int[]{startColor, endColor});
drawable.setAlpha(0x4d);
stateListDrawable.addState(new int[]{android.R.attr.state_pressed}, drawable);
view.setBackgroundDrawable(stateListDrawable);
以上内容中:
1.StateListDrawable来实现动态Selector效果
2.android.R.attr.state_pressed为点击效果,-android.R.attr.state_pressed为非点击效果(示例中调整了透明度来区别)
3.GradientDrawable为设置背景渐变色