Search code examples
androidstatelistdrawableanimator

How to define (programmatically) a transition in AnimatedStateListDrawable


The new drawable selector AnimatedStateListDrawable allows to define animations when the selector goes from one state to another.
In the documentation, and so far in the web, there are only examples of XML definitions of this new class.
My problem is: I want to create it programmatically:

    AnimatedStateListDrawable astld= new AnimatedStateListDrawable();
    astld.addState(KEY_STATE_PRESSED, pressedKey);
    astld.addState(StateSet.WILD_CARD, normalKey);
    astld.addTransition(??????????????);

but I cannot find where can I get, or set, the states IDs (fromId and toId) needed for the transition.

public void addTransition (int fromId, int toId, T transition, boolean reversible)
Added in API level 21
Adds a new transition between keyframes.

Parameters:
fromId Unique identifier of the starting keyframe
toId Unique identifier of the ending keyframe
transition An Animatable drawable to use as a transition, may not be null
reversible Whether the transition can be reversed


Solution

  • I found finally that there is a new method addState() with a different signature, which includes the parameter for the ID.

    public void addState (int[] stateSet, Drawable drawable, int id)
    Added in API level 21
    Add a new drawable to the set of keyframes.

    Parameters
    stateSet An array of resource IDs to associate with the keyframe
    drawable The drawable to show when in the specified state, may not be null
    id The unique identifier for the keyframe