获取xml里设置的statelistdrawable内的各个状态对应的drawable

来源:互联网 发布:mac windows安装u盘 编辑:程序博客网 时间:2024/06/05 04:35

因为StatelistDrawable内获取状态以及drawable的方法都是被隐藏的,所以只有利用java的反射机制来获取各个状态,以及各个状态对应的drawable

StateListDrawable userDrawable = (StateListDrawable) mResources.getDrawable(backGround);

Class slDraClass = StateListDrawable.class;
Method getStateCountMethod = slDraClass.getDeclaredMethod("getStateCount", null);
Method getStateSetMethod = slDraClass.getDeclaredMethod("getStateSet", int.class);
Method getDrawableMethod = slDraClass.getDeclaredMethod("getStateDrawable", int.class);
int count = (Integer) getStateCountMethod.invoke(userDrawable, null);
Log.d(TAG, "state count ="+count);
for(int i=0;i < count;i++){
int[] stateSet = (int[]) getStateSetMethod.invoke(userDrawable, i);
if(stateSet == null|| stateSet.length ==0){
Log.d(TAG, "state is null");
}else{
for(int j=0;j<stateSet.length;j++){
Log.d(TAG, "state ="+stateSet[j]);
if(stateSet[j] == -ENABLEED){
Log.d(TAG, "enabled false");
hasFalseEnabledDrawable = true;
Drawable drawable = (Drawable) getDrawableMethod.invoke(userDrawable, i);//这就是你要获得的Enabled为false时候的drawable

newDrawable.addState(new int[]{-ENABLEED}, drawable);

}

}

0 0
原创粉丝点击