首页 > 代码库 > StateListDrawable

StateListDrawable

Integer[] mButtonState = { R.drawable.defaultbutton,
                R.drawable.focusedpressed, R.drawable.pressed };
Button mButton = (Button) findViewById(R.id.button);
mButton.setBackgroundDrawable(myButton.setbg(mButtonState));

public StateListDrawable setbg(Integer[] mImageIds) {
            StateListDrawable bg = new StateListDrawable();
            Drawable normal = this.getResources().getDrawable(mImageIds[0]);
            Drawable selected = this.getResources().getDrawable(mImageIds[1]);
            Drawable pressed = this.getResources().getDrawable(mImageIds[2]);
            bg.addState(View.PRESSED_ENABLED_STATE_SET, pressed);
            bg.addState(View.ENABLED_FOCUSED_STATE_SET, selected);
            bg.addState(View.ENABLED_STATE_SET, normal);
            bg.addState(View.FOCUSED_STATE_SET, selected);
            bg.addState(View.EMPTY_STATE_SET, normal);
            return bg;
}

在输入法中有如下的使用
StateListDrawable mStateListDrawable = new StateListDrawable();
                mStateListDrawable.addState(new int[] { android.R.attr.state_pressed }, getResources().getDrawable(mKeyBackgroundId));
                mStateListDrawable.addState(new int[0], getResources().getDrawable(R.drawable.transparent));

StateListDrawable 可以通过如下的方法获取点击态的drawable:
        StateListDrawable drawable = ((StateListDrawable)background);
        drawable.setState(new int[]{android.R.attr.state_focused,android.R.attr.state_pressed});


来自为知笔记(Wiz)


StateListDrawable