gpt4 book ai didi

android - 当 clickable 为 false 时更改 Button 的背景颜色

转载 作者:搜寻专家 更新时间:2023-11-01 09:00:01 25 4
gpt4 key购买 nike

当程序员在 XML 布局文件中指定按钮不可点击时,我试图通过选择器更改按钮的颜色。 IE。 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"/>

最佳答案

不幸的是,StateListDrawable 没有state_clickable 属性。您可以通过两种方式解决问题:

  1. 在调用 setClickable() 时更改 View 的背景。
  2. 引入您自己的 state_clickable 选择器状态。

如果您更喜欢第二种方式,您需要在项目中添加以下更改:

attrs.xml

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

MyButton.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();
}

background.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>

但是这个解决方案有一个非常明显的弱点。如果您想在不同的 View 类中使用此状态,则必须将这些类子类化,并将 MyButton.java 中的代码添加到它们中。

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com