首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何以编程方式更改StateListDrawable?

如何以编程方式更改StateListDrawable?
EN

Stack Overflow用户
提问于 2019-05-21 05:15:54
回答 2查看 1.1K关注 0票数 0

有没有什么方法可以通过编程的方式改变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“。有没有办法通过编程改变它的状态?

EN

回答 2

Stack Overflow用户

发布于 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
票数 3
EN

Stack Overflow用户

发布于 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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56228276

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档