Question

I have created a custom view class that extends ImageButton. I did so because there this new button class allowed me to do some animations.

The actual problem that I have is the following: When I click on the button, I want it to change its image drawable. However, when I set a new image like this

private void setCustomButtonIcon() {
    if (mEnabled) {
        myCustomButton.setImageResource(R.drawable.mybutton_off);
    } else {
        myCustomButton.setImageResource(R.drawable.mybutton_on);
    }
}

then the rotation that it had, since it may have been rotated during the animation, is not preserved.

Now, the obvious idea is to override setImageResource in my custom button class. How can I do that so that the rotation of the button is preserved?

Was it helpful?

Solution

I think your problem is related to another issue:

Most likely, you are using the Animation class for your animations. So you probably used the RotationAnimation superclass, did something like

RotateAnimation animation = new RotateAnimation(
    fromDegrees, toDegress, pivotX, pivotY);

and applied that animation to your custom button.

However, as it turns out, this only animates a bitmap representation of your button. Or, in other words, the actual button/ view does not get rotated and remains in his orientation.

Therefore, every call to onDraw(), like it happens when you click on the button, will "reset the look" of your button.

So, what you probably want to use is an ObjectAnimator. This will animate the whole view and fix your problem with preserving the state of the object.

You can use the animator just like this, for example:

ObjectAnimator.ofFloat(myButton, "rotation", fromDegrees, -toDegrees)
            .setDuration(animationDuration)
            .start();

Note: ObjectAnimator was added in API 11. So if you are targeting older versions then you should use Jake Whartons nineoldandroids library. (Download the .jar file and add it to your libs folder in you project.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top