Android setButtonDrawable()的兼容问题解决办法
Android setButtonDrawable()的兼容问题解决办法
setButtonDrawable()的兼容问题
API16实现
/** *SetthebackgroundtoagivenDrawable,identifiedbyitsresourceid. * *@paramresidtheresourceidofthedrawabletouseasthebackground */ publicvoidsetButtonDrawable(intresid){ if(resid!=0&&resid==mButtonResource){ return; } mButtonResource=resid; Drawabled=null; if(mButtonResource!=0){ d=getResources().getDrawable(mButtonResource); } setButtonDrawable(d); } /** *SetthebackgroundtoagivenDrawable * *@paramdTheDrawabletouseasthebackground */ publicvoidsetButtonDrawable(Drawabled){ if(d!=null){ if(mButtonDrawable!=null){ mButtonDrawable.setCallback(null); unscheduleDrawable(mButtonDrawable); } d.setCallback(this); d.setState(getDrawableState()); d.setVisible(getVisibility()==VISIBLE,false); mButtonDrawable=d; mButtonDrawable.setState(null); setMinHeight(mButtonDrawable.getIntrinsicHeight()); } refreshDrawableState(); }
API23实现
/** *Setsadrawableasthecompoundbuttonimagegivenitsresource *identifier. * *@paramresIdtheresourceidentifierofthedrawable *@attrrefandroid.R.styleable#CompoundButton_button */ publicvoidsetButtonDrawable(@DrawableResintresId){ finalDrawabled; if(resId!=0){ d=getContext().getDrawable(resId); }else{ d=null; } setButtonDrawable(d); } /** *Setsadrawableasthecompoundbuttonimage. * *@paramdrawablethedrawabletoset *@attrrefandroid.R.styleable#CompoundButton_button */ @Nullable publicvoidsetButtonDrawable(@NullableDrawabledrawable){ if(mButtonDrawable!=drawable){ if(mButtonDrawable!=null){ mButtonDrawable.setCallback(null); unscheduleDrawable(mButtonDrawable); } mButtonDrawable=drawable; if(drawable!=null){ drawable.setCallback(this); drawable.setLayoutDirection(getLayoutDirection()); if(drawable.isStateful()){ drawable.setState(getDrawableState()); } drawable.setVisible(getVisibility()==VISIBLE,false); setMinHeight(drawable.getIntrinsicHeight()); applyButtonTint(); } } }
结论
RadioButton和CheckBox都是Androidapp中常用的Widget,它们派生于CompoundButton,允许使用者自行设置背景和按钮的样式,不过,有时我们仅希望简单的设置一个有状态的背景,并隐藏其默认样式。可是,当我们调用setButtonDrawable(null)或setButtonDrawable(0)时,却发现完全没有效果。原来,CompoundButton的setButtonDrawable的代码实现中屏蔽了null或resid为0的Drawable,迫使我们必须传入有效的Drawable对象。
这时候,透明颜色就可以派上用场了:
button.setButtonDrawable(newColorDrawable(Color.TRANSPARENT));
参考:
隐藏RadioButton,CheckBox图片setButtonDrawable:
RadioButton和CheckBox都是Androidapp中常用的Widget,它们派生于CompoundButton,允许使用者自行设置背景和按钮的样式,不过,有时我们仅希望简单的设置一个有状态的背景,并隐藏其默认样式。可是,当我们调用setButtonDrawable(null)或setButtonDrawable(0)时,却发现完全没有效果。原来,CompoundButton的setButtonDrawable的代码实现中屏蔽了null或resid为0的Drawable,迫使我们必须传入有效的Drawable对象。
这时候,透明颜色就可以派上用场了:
button.setButtonDrawable(newColorDrawable(Color.TRANSPARENT));
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!