代码中设置状态选择器

来源:互联网 发布:广数g76内锥螺纹编程 编辑:程序博客网 时间:2024/06/11 03:10

Android 设置状态选择器一般在xml中设置selecter,在代码中也可以设置状态选择器

ImageView mImageView;/* 通过设置setBackgroundDrawable,设置选择器*/mImageView.setBackgroundDrawable(addStateDrawable(mContext, R.drawable.newfolder_popu_nomal, R.drawable.newfolder_popu_focus, R.drawable.newfolder_popu_focus));/*** 设置资源的id*/public static 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;    }
0 0
原创粉丝点击