Rotating a view in Android

Viewed 133000

I have a button that I want to put on a 45 degree angle. For some reason I can't get this to work.

Can someone please provide the code to accomplish this?

13 Answers

Extend the TextView class and override the onDraw() method. Make sure the parent view is large enough to handle the rotated button without clipping it.

@Override
protected void onDraw(Canvas canvas) {
     canvas.save();
     canvas.rotate(45,<appropriate x pivot value>,<appropriate y pivot value>);
     super.onDraw(canvas);
     canvas.restore();

} 

I just used the simple line in my code and it works :

myCusstomView.setRotation(45);

Hope it works for you.

As mentioned before, the easiest way it to use rotation available since API 11:

android:rotation="90"    // in XML layout

view.rotation = 90f      // programatically

You can also change pivot of rotation, which is by default set to center of the view. This needs to be changed programatically:

// top left
view.pivotX = 0f
view.pivotY = 0f

// bottom right
view.pivotX = width.toFloat()
view.pivotY = height.toFloat()

...

In Activity's onCreate() or Fragment's onCreateView(...) width and height are equal to 0, because the view wasn't measured yet. You can access it simply by using doOnPreDraw extension from Android KTX, i.e.:

view.apply {
    doOnPreDraw {
        pivotX = width.toFloat()
        pivotY = height.toFloat()
    }
}

if you wish to make it dynamically with an animation:

view.animate()
    .rotation(180)
    .start();

THATS IT

fun rotateArrow(view: View): Boolean {
    return if (view.rotation == 0F) {
        view.animate().setDuration(200).rotation(180F)
        true
    } else {
         view.animate().setDuration(200).rotation(0F)
         false
    }
}

That's simple, in Java

your_component.setRotation(15);

or

your_component.setRotation(295.18f);

in XML

<Button android:rotation="15" />
Related