[英]how to change StateListDrawable programmatically?
Is there any way 'state' can be changed programmatically for StateListDrawable? 是否有任何方式可以通过编程方式为StateListDrawable更改“状态”?
<selector xmlns:android="http://schemas.android.com/apk/res/android" android:exitFadeDuration="@android:integer/config_shortAnimTime">
<item
android:state_checked="true"
android:drawable="@drawable/picker_circle_selected"/>
<item
android:state_checked="false"
android:drawable="@drawable/picker_circle_today" />
StateListDrawable backgroundDrawable = (StateListDrawable) ContextCompat.getDrawable(getContext(), R.drawable.picker_selector);
I have tried ....." selectDrawable(int index)
" and " addState()
" on StateListDrawable
. 我曾尝试...... “ selectDrawable(int index)
”和“ addState()
的” StateListDrawable
。 But nothing worked. 但没有任何效果。
By default " state_checked = false
" drawable gets displayed. 默认情况下会显示“ state_checked = false
”drawable。 When user taps on this drawable it changes it's state to " state_checked = true
". 当用户点击这个drawable时,它会将状态更改为“ state_checked = true
”。 Is there any way it's state can be changed programmatically? 有没有什么方法可以通过编程方式更改状态?
you can change the color of the stat using LayerDrawable
您可以使用LayerDrawable
更改stat的颜色
DrawableContainerState drawableContainerState = (DrawableContainerState) backgroundDrawable.getConstantState();
Drawable[] children = drawableContainerState.getChildren();
LayerDrawable selectedItem = (LayerDrawable) children[0];
LayerDrawable unselectedItem = (LayerDrawable) children[1];
selectedItem.setColor(Color.Black); // changing to black color
Try this 尝试这个
// call your view
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(yourlayout, viewGroup, false);
ColorDrawable colorDrawableSelected = new ColorDrawable(context.getResources().getColor(R.color.white));
StateListDrawable stateListDrawable = new StateListDrawable();
stateListDrawable.addState(new int[]{android.R.attr.state_selected}, colorDrawableSelected);
stateListDrawable.addState(StateSet.WILD_CARD, null);// set the StateListDrawable as background of the view
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
view.setBackgroundDrawable(stateListDrawable);
} else {
view.setBackground(stateListDrawable);
then call like this: view.setSelected etc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.