android - 如何从 View.getDrawableState() 中识别状态

标签 android android-view android-ui android-resources android-drawable

我正在尝试创建一个自定义按钮,根据按钮状态(按下、启用等)更改其阴影属性(半径、距离等)

我最终承认这不能使用 XML 选择器来完成,所以我覆盖了 View.drawableStateChanged(),并尝试使用 View.getDrawableState() 找出当前状态。

但是,此函数返回一个 int[],我无法弄清楚此值的含义,也无法从中提取各个状态。 该文档纯粹是废话:

public final int[] getDrawableState ()

Added in API level 1

Return an array of resource IDs of the drawable states representing the current state of the view.

Returns The current drawable state

我也没有在网上找到例子,相关的Android源代码非常神秘。

那么,例如,您如何从这个 int[] 中找出按钮的当前“按下”状态是什么?还是“启用状态”?

最佳答案

我只是通过反复试验自己想出来的。

该列表包含“真”状态的资源标识符,不包含“假”状态的标识符。 以下代码满足了我的需求:

// Get the relevant drawable state
boolean statePressed = false, stateEnabled = false;
int[] states = getDrawableState();
for (int state : states)
{
    if (state == android.R.attr.state_enabled)
        stateEnabled = true;
    else if (state == android.R.attr.state_pressed)
        statePressed = true;
}

关于android - 如何从 View.getDrawableState() 中识别状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24795818/

相关文章:

android - 结合使用 Google 的 Drive API 和 Spreadsheets API 会导致 "Unable to execute dex: Multiple dex files define..."错误

android - 从默认蓝色更改抽屉导航选择的项目颜色

android - 将 View 移出约束布局

android - 如何从库项目中引用应用程序主题属性?

android - 当 View 在 Android 屏幕上可见时如何获得回调

android - 在 Heroku 上为 Parse-server-example 设置 Mailgun

java - 通过蓝牙在 Android 手机和运行 OS X 的笔记本电脑之间发送数据

java - 如何更改 SearchView 下方底线的颜色

android - setTranslation 不适用于 onCreate()

android 文件传输到 wifi 打印机