有没有什么方法可以通过编程的方式改变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);
我在StateListDrawable
上试过……“selectDrawable(int index)
”和"addState()
“。但都不管用。
默认情况下,会显示"state_checked = false
“可绘制内容。当用户点击这个可绘制文件时,它的状态就会变为"state_checked = true
“。有没有办法通过编程改变它的状态?
发布于 2019-05-21 06:53:42
尝尝这个
// 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
发布于 2019-05-21 06:03:46
您可以使用LayerDrawable
更改状态的颜色
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
https://stackoverflow.com/questions/56228276
复制相似问题