是否可以通过编程方式为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);
我在selectDrawable(int index)
上尝试了.....“ addState()
”和“ StateListDrawable
”。但没有任何效果。
默认显示“ state_checked = false
”可绘制对象。当用户点击此可绘制对象时,它的状态更改为“ state_checked = true
”。可以通过编程方式更改其状态吗?
答案 0 :(得分:0)
您可以使用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
答案 1 :(得分:0)
尝试一下
// 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