1

I'd like to gradually rotate one of my buttons in my Android application with the following code:

  for(int i=0; i<90; i++)
  {
        myButton.setRotation(i);
        try 
        {
            Thread.sleep(5);
        } 
        catch (Exception e) 
        {
            e.printStackTrace();
        }
  }

The sleep is only there to have a bit of a delay between the phases.

Once I run the code the button rotates by 90 degrees, but without gradually rotating, it simply jumps to 90 rotation.

How should I modify my code to show the in-between states as well?

ॐ Rakesh Kumar
  • 1,318
  • 1
  • 14
  • 24
Istvanb
  • 392
  • 2
  • 6
  • 19
  • 1
    It is better to use animation to rotate your button, maybe this link will be helpful : https://www.viralandroid.com/2015/11/android-rotate-animation-example.html and this link : https://www.tutlane.com/tutorial/android/android-rotate-animations-clockwise-anti-clockwise-with-examples – Shayan Tabatabaee Oct 09 '18 at 09:30
  • 2
    use like this `myButton.animate().rotation(90).setDuration(1000).setInterpolator(new AccelerateInterpolator());` – Farrokh Oct 09 '18 at 09:32
  • 1
    did you try this solution https://stackoverflow.com/questions/1634252/how-to-make-a-smooth-image-rotation-in-android – Manikandan K Oct 09 '18 at 09:33
  • 1
    Do not use `sleep` method in your main thread, because it freezes the UI. If you want to introduce a delay, use `Handler.postDelayed` method. – Piotr Aleksander Chmielowski Oct 09 '18 at 09:33

2 Answers2

1

create xml file in your anim folder name rotate_ninety

<rotate
    android:duration="2500"
    android:interpolator="@android:anim/linear_interpolator"
    android:pivotX="50%"
    android:pivotY="50%"
    android:repeatCount="infinite"
    android:repeatMode="restart"
    android:toDegrees="90" />

then replace your loop with this code

    Animation animation = AnimationUtils.loadAnimation(this, R.anim.rotate_ninety);
    myButton.startAnimation(animation);
Nirav Joshi
  • 1,713
  • 15
  • 28
0

You can try this code to rotate your button:

long rotation = 90; //insert number of degrees here

myButton.animate()
     .rotation(rotation)
     .setDuration(500) //500 is half a second
     .setStartDelay(100) //this is optional
     .start();

For extra information on the ViewPropretyAnimator, look here.

476rick
  • 2,764
  • 4
  • 29
  • 49