赞
踩
Android里面经常会使用shape或者selector来定制一些View的背景。那么如果想要动态更改shape或者seletor文件中的颜色值,该怎么处理呢?
一、Java代码更改shape的颜色值
shape文件如下:
Java代码如下:
GradientDrawable myGrad =(GradientDrawable)view.getBackground();
myGrad.setColor(ContextCompat.getColor(mContext,R.color.spinnerpop_notedit_bg_color));myGrad.setStroke(2,ContextCompat.getColor(mContext,R.color.spinnerpop_notedit_bg_color));
二、Java代码更改selector的颜色值
selector文件如下:
java代码如下:
因为StatelistDrawable内获取状态以及drawable的方法都是被隐藏的,所以只有利用Java的反射机制来获取各个状态,以及各个状态对应的drawable。
StateListDrawable mySelectorGrad =(StateListDrawable)view.getBackground();try{
Class slDraClass= StateListDrawable.class;
Method getStateCountMethod= slDraClass.getDeclaredMethod("getStateCount", new Class[0]);
Method getStateSetMethod= slDraClass.getDeclaredMethod("getStateSet", int.class);
Method getDrawableMethod= slDraClass.getDeclaredMethod("getStateDrawable", int.class);int count = (Integer) getStateCountMethod.invoke(mySelectorGrad, new Object[]{});//对应item标签
Log.d(TAG, "state count ="+count);for(int i=0;i < count;i++) {int[] stateSet = (int[]) getStateSetMethod.invoke(mySelectorGrad, i);//对应item标签中的 android:state_xxxx
if (stateSet == null || stateSet.length == 0) {
Log.d(TAG,"state is null");
GradientDrawable drawable= (GradientDrawable) getDrawableMethod.invoke(mySelectorGrad, i);//这就是你要获得的Enabled为false时候的drawable
drawable.setColor(Color.parseColor(checkColor));
}else{for (int j = 0; j < stateSet.length; j++) {
Log.d(TAG,"state =" +stateSet[j]);
Drawable drawable= (Drawable) getDrawableMethod.invoke(mySelectorGrad, i);//这就是你要获得的Enabled为false时候的drawable
}
}
}
}catch(NoSuchMethodException e) {
e.printStackTrace();
}catch(InvocationTargetException e) {
e.printStackTrace();
}catch(IllegalAccessException e) {
e.printStackTrace();
}
android:state_focused 对应的Java中的整型值 : android.R.attr.state_focused,如果为false,则对应 - android.R.attr.state_focused【“-”负号表示对应的属性值为false】
android:state_pressed 对应的Java中的整型值 : android.R.attr.state_pressed,如果为false,则对应 - android.R.attr.state_pressed【“-”负号表示对应的属性值为false】
参考资料
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。