Android(安卓)动态创建Drawable selector
16lz
2021-01-26
创建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);
更多相关文章
- Android底层字符传递给上层应用举例
- Android(安卓)View的onClick回调机制
- 加快Android(安卓)Stduio编译速度方法之一
- Android的ViewPager中移除Fragment
- 【Android】结束活动退出程序的方法
- Android(安卓)Handler的使用!!!
- Android中实现圆角图片的几种方法
- Android(安卓)adapter has changed解决方法
- Android自定义组件系列【11】——实现3D立体旋转效果