java代码中实现android背景选择的selector-StateListDrawable的应用

  

首先定义一个获得StateListDrawable对象的方法:

 
private StateListDrawable addStateDrawable(Context context,  int idNormal, int idPressed, int idFocused) {
    StateListDrawable sd = new StateListDrawable();
    Drawable normal = idNormal == -1 ? null : context.getResources().getDrawable(idNormal);
    Drawable pressed = idPressed == -1 ? null : context.getResources().getDrawable(idPressed);
    Drawable focus = idFocused == -1 ? null : context.getResources().getDrawable(idFocused);
    //注意该处的顺序,只要有一个状态与之相配,背景就会被换掉
    //所以不要把大范围放在前面了,如果sd.addState(new[]{},normal)放在第一个的话,就没有什么效果了
    sd.addState(new int[]{android.R.attr.state_enabled, android.R.attr.state_focused}, focus);
    sd.addState(new int[]{android.R.attr.state_pressed, android.R.attr.state_enabled}, pressed);
    sd.addState(new int[]{android.R.attr.state_focused}, focus);
    sd.addState(new int[]{android.R.attr.state_pressed}, pressed);
    sd.addState(new int[]{android.R.attr.state_enabled}, normal);
    sd.addState(new int[]{}, normal);
    return sd;
}

其中,就如注释中所讲的addState的顺序相当重要。

使用ddStateDrawable

 
//……前面对Button的声明略去
okBtn.setBackgroundDrawable(addStateDrawable(this, R.drawable.btn_normal, R.drawable.btn_selected, R.drawable.btn_selected));
cancelBtn.setBackgroundDrawable(addStateDrawable(this, R.drawable.btn_normal, R.drawable.btn_selected, R.drawable.btn_selected));

  
    // Bitmap转换成Drawable
    public Drawable bitmap2Drawable(Bitmap bitmap) {
        BitmapDrawable bd = new BitmapDrawable(getResources(), bitmap);
        Drawable d = (Drawable) bd;
        return d;
    }

    private StateListDrawable addStateDrawable(Bitmap idNormal, Bitmap idPressed, Bitmap idFocused) {
        StateListDrawable sd = new StateListDrawable();
        Drawable normal = bitmap2Drawable(idNormal);
        Drawable pressed = bitmap2Drawable(idPressed);
        Drawable focus = bitmap2Drawable(idFocused);
        //注意该处的顺序,只要有一个状态与之相配,背景就会被换掉
        //所以不要把大范围放在前面了,如果sd.addState(new[]{},normal)放在第一个的话,就没有什么效果了
        sd.addState(new int[]{android.R.attr.state_enabled, android.R.attr.state_focused}, focus);
        sd.addState(new int[]{android.R.attr.state_pressed, android.R.attr.state_enabled}, pressed);
        sd.addState(new int[]{android.R.attr.state_focused}, focus);
        sd.addState(new int[]{android.R.attr.state_pressed}, pressed);
        sd.addState(new int[]{android.R.attr.state_enabled}, normal);
        sd.addState(new int[]{}, normal);
        return sd;
    }
   
原文地址:https://www.cnblogs.com/niray/p/4602919.html