Is there any way to make an image rotate for example by 90 degrees when clicked on it? I want that by clicking on the image, it takes a turn, like a clock hand for example.
Is there any way to make an image rotate for example by 90 degrees when clicked on it? I want that by clicking on the image, it takes a turn, like a clock hand for example.
Only animate().rotation(angle).start()
within the setOnClickListener
method of your button would already solve the problem. Thus, it is enough to define a value for the variable angle
, which would refer to the desired angle. See:
int angle = 90;
imageView.animate().rotation(angle).start();
In the onClick
method of your image, add the following code:
imageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
imageView.animate().rotation(90).start();
}
});
Create the button_rotate.xml
file in the anim
folder within your project:
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/animation"
android:duration="1000"
android:fromDegrees="0"
android:interpolator="@android:anim/linear_interpolator"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="90" />
Now create the animation in your Java class, more precisely, within the onClick
method of your image:
/* Pega a sua ImageView*/
ImageView iv = (ImageView) view.findViewById(R.id.your_image_view);
/* Cria a animação */
Animation rotation = AnimationUtils.loadAnimation(context, R.anim.animation);
rotation.setRepeatCount(Animation.INFINITE);
/* Inicia a animação */
iv.startAnimation(rotation);
To stop the animation:
iv.clearAnimation();
Translated and adapted from: Rotate image
Use the component's View ## SetRotation () ImageView .
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
imageView.setRotation(90);
}
});
The 90 can be any value, and if you want to add a rotation, that is, get the current rotation of the view and apply another value, just get the rotation with getRotation and add the its value.
imageView.setRotation(imageView.getRotation() + valor);
If the rotation is 90, the new rotation will be 180, and so on.
Obs : As the author of the post said, this method only applies a rotation in the image, it does not cause an animation in it.
To rotate the image with an animation, you can use the LinearInterpolator
imageView.animate().rotationBy(90).setDuration(300).setInterpolator(new LinearInterpolator()).start();
Where :
You can use other attributes, such as withStartAction
, as its name says, when the animation starts, it allows you to apply an action in the view, for example, to apply an animation to another view or to itself. >
imageView.animate().rotationBy(90).withStartAction(new Runnable(){
public void run(){
imageView.setRotation(90);
}
}).setDuration(300).setInterpolator(new LinearInterpolator());