如何从View.getDrawableState()识别状态 [英] How to identify the state from View.getDrawableState()

查看:115
本文介绍了如何从View.getDrawableState()识别状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm attempting to create a custom Button that changes its shadow attributes (radius, distance, etc.) based on button state (pressed, enabled, etc.)

我最终接受了使用XML选择器无法完成的操作,因此我重写了View.drawableStateChanged(),并尝试使用View.getDrawableState()找出当前状态.

I finally accepted that this can't be done using XML selectors, so I override View.drawableStateChanged(), and attempt to figure out the current state using View.getDrawableState().

但是,此函数返回一个int [],我无法弄清楚该值的含义,以及如何从中提取单个状态.该文档纯属废话:

However, this function returns an int[], and I couldn't possibly figure out what this value means, and how do I extract individual states from it. The documentation is pure crap:

公共最终int [] getDrawableState()

public final int[] getDrawableState ()

已添加到API级别1

Added in API level 1

返回表示以下内容的可绘制状态的资源ID的数组视图的当前状态.

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

返回当前可绘制状态

我也没有找到在线示例,与此相关的Android源代码是高度神秘的.

I also failed to find online examples, and the Android source code related to that is highly cryptic.

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

So, how do you figure out from this int[] what is the current "pressed" state of the button, for example? Or the "enabled state"?

推荐答案

我只是通过反复试验自己弄清楚了.

I just figured it out on my own by trial and error.

该列表包含"true"状态的资源标识符,不包含"false"状态的标识符.以下代码满足了我的需求:

The list contains resource identifiers of the "true" states, and does not contain the identifiers of "false" states. The following code addresses my needs:

// 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;
}

这篇关于如何从View.getDrawableState()识别状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆