当程序员在XML布局文件中指定按钮不可访问时,我正试图通过选择器更改按钮的颜色。例如,android:clickable="false"这是我当前的选择器xml文件,它似乎无法正常工作。

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
       <item android:state_enabled="false">
        <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">
            <solid android:color="#FF00FF"/>
            <corners
            android:bottomRightRadius="16dp"
            android:bottomLeftRadius="16dp"
            android:topRightRadius="16dp"
            android:topLeftRadius="16dp"/>
        </shape>
    </item>

<item android:state_pressed="true">
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
        <solid android:color="#CDAF95"/>
        <corners
        android:bottomRightRadius="16dp"
        android:bottomLeftRadius="16dp"
        android:topRightRadius="16dp"
        android:topLeftRadius="16dp"/>
    </shape>
</item>

<item>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#D2B48C"/>
    <corners
    android:bottomRightRadius="16dp"
    android:bottomLeftRadius="16dp"
    android:topRightRadius="16dp"
    android:topLeftRadius="16dp"/>

最佳答案

不幸的是,state_clickable没有StateListDrawable属性。你可以用两种方法解决这个问题:
调用setClickable()时,更改视图的背景。
介绍您自己的选择器状态。
如果您喜欢第二种方式,则需要将以下更改添加到项目中:
属性.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ClickableState">
        <attr name="state_clickable" format="boolean" />
    </declare-styleable>
</resources>

我的按钮.java
private static final int[] STATE_CLICKABLE = {R.attr.state_clickable};

@Override
protected int[] onCreateDrawableState(final int extraSpace) {
    if (isClickable()) {
        final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
        mergeDrawableStates(drawableState, STATE_CLICKABLE);
        return drawableState;
    } else {
        return super.onCreateDrawableState(extraSpace);
    }
}

@Override
public void setClickable(final boolean clickable) {
    super.setClickable(clickable);
    refreshDrawableState();
}

背景.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:auto="http://schemas.android.com/apk/res-auto">
    <item auto:state_clickable="false">
        <!-- non-clickable shape here -->
    </item>

    <!-- other shapes -->
</selector>

但这种解决方案有一个非常明显的弱点。如果要在不同的视图类中使用此状态,则必须对这些类进行子类化,并向它们添加state_clickable中的代码。

关于android - 当clickable为false时更改Button的背景颜色,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15862988/

10-14 20:24
查看更多