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

本文介绍了一个用于Android开发的方法addStateDrawable,通过该方法可以根据不同的状态设置按钮或其他UI元素的背景图片。具体状态包括正常状态、按下状态及获得焦点状态。

http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2014/0924/1712.html

 

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;
}

 

转载于:https://www.cnblogs.com/weidingqiang/p/5070435.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值