动态生成selector选择器
首先动态生成drawable
GradientDrawable pressed=new GradientDrawable();
pressed.setColor(Color.parseColor("#ff0000"));
GradientDrawable normal=new GradientDrawable();
normal.setColor(Color.parseColor("#44000000"));
normal.setShape(GradientDrawable.OVAL);
normal为圆型,灰色,pressed为红色
也可以用静态drawable
Drawable normal = getResources().getDrawable(R.drawable.point_pressed);
Drawable pressed = getResources().getDrawable(R.drawable.point_normal);
point_pressed.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#ff0000"/>
</shape>
point_normal.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<solid android:color="#ff0000"/>
</shape>
生成选择器,用一个Button做测试
Button button=findViewById(R.id.btn);
StateListDrawable bg = new StateListDrawable();
Drawable normal = getResources().getDrawable(R.drawable.point_pressed);
Drawable pressed = getResources().getDrawable(R.drawable.point_normal);
bg.addState(new int[]{android.R.attr.state_pressed}, pressed);
bg.addState(new int[]{}, normal);
button.setBackground(bg);
得到结果
未按下状态
按下状态