当前位置:   article > 正文

java改颜色代码_Java代码更改shape和selector文件的颜色值

java shp设置颜色

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】

参考资料

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/293726
推荐阅读
相关标签
  

闽ICP备14008679号