Android 动态创建Drawable selector

创建selector有两种方法,一种是定义xml文件,一种是创建StateListDrawable对象,完全可以用创建StateListDrawable来代替xml,它的好处是可以在程序运行时动态的调整背景颜色或者背景图片。

一.xml创建selector方法如下:
定义一个switch_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/switch_bg_disabled_emui" android:state_enabled="false"/>
    <item android:drawable="@drawable/switch_bg_on_emui" android:state_pressed="true"/>
    <item android:drawable="@drawable/switch_bg_on_emui" android:state_focused="true"/>
    <item android:drawable="@drawable/switch_bg_on_emui" android:state_checked="true"/>
    <item android:drawable="@drawable/switch_bg_off_emui"/>
</selector>

在Activity按下面方法使用

Drawable drawable = getResourse().getDrawable(R.drawable.switch_selector);
ImageView iv = new ImageView(this);
iv.setBackground(drawable);

二.用StateListDrawable来代替xml创建selector:

        private StateListDrawable createDrawableSelector(Context context)
        {
            Drawable checked = context.getResources().getDrawable(R.drawable.switch_bg_on_emui);
            Drawable unchecked = context.getResources().getDrawable(R.drawable.switch_bg_off_emui);
            Drawable disabled = context.getResources().getDrawable(R.drawable.switch_bg_disabled_emui);
            StateListDrawable stateList = new StateListDrawable();
            int statePressed = android.R.attr.state_pressed;
            int stateChecked = android.R.attr.state_checked;
            int stateFocused = android.R.attr.state_focused;
            int stateensable = android.R.attr.state_enabled;
            stateList.addState(new int[] {-stateensable}, disabled);
            stateList.addState(new int[] {stateChecked}, checked);
            stateList.addState(new int[] {statePressed}, checked);
            stateList.addState(new int[] {stateFocused}, checked);
            stateList.addState(new int[] {}, unchecked);
            return stateList;
        }

其中stateList.addState()表示一个状态对应一个Drawable,在Activity里面按下面方法使用

Drawable drawable = createDrawableSelector(this);
ImageView iv = new ImageView(this);
iv.setBackground(drawable);
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值