SirKnigget
SirKnigget

Reputation: 3644

How to identify the state from 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.)

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().

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:

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

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

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

Upvotes: 5

Views: 4360

Answers (1)

SirKnigget
SirKnigget

Reputation: 3644

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

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

Upvotes: 13

Related Questions