[android] Rotating a view in Android

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?

This question is related to android view rotation

The answer is


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
    }
}

API 11 added a setRotation() method to all views.


@Ichorus's answer is correct for views, but if you want to draw rotated rectangles or text, you can do the following in your onDraw (or onDispatchDraw) callback for your view:

(note that theta is the angle from the x axis of the desired rotation, pivot is the Point that represents the point around which we want the rectangle to rotate, and horizontalRect is the rect's position "before" it was rotated)

canvas.save();
canvas.rotate(theta, pivot.x, pivot.y);
canvas.drawRect(horizontalRect, paint);
canvas.restore();

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

myCusstomView.setRotation(45);

Hope it works for you.


if you wish to make it dynamically with an animation:

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

THATS IT


Applying a rotation animation (without duration, thus no animation effect) is a simpler solution than either calling View.setRotation() or override View.onDraw method.

// substitude deltaDegrees for whatever you want
RotateAnimation rotate = new RotateAnimation(0f, deltaDegrees, 
    Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);  

// prevents View from restoring to original direction. 
rotate.setFillAfter(true); 

someButton.startAnimation(rotate);

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();

} 

You could create an animation and apply it to your button view. For example:

    // Locate view
    ImageView diskView = (ImageView) findViewById(R.id.imageView3);

    // Create an animation instance
    Animation an = new RotateAnimation(0.0f, 360.0f, pivotX, pivotY);

    // Set the animation's parameters
    an.setDuration(10000);               // duration in ms
    an.setRepeatCount(0);                // -1 = infinite repeated
    an.setRepeatMode(Animation.REVERSE); // reverses each repeat
    an.setFillAfter(true);               // keep rotation after animation

    // Aply animation to image view
    diskView.setAnimation(an);

That's simple, in Java

your_component.setRotation(15);

or

your_component.setRotation(295.18f);

in XML

<Button android:rotation="15" />

Joininig @Rudi's and @Pete's answers. I have created an RotateAnimation that keeps buttons functionality also after rotation.

setRotation() method preserves buttons functionality.

Code Sample:

Animation an = new RotateAnimation(0.0f, 180.0f, mainLayout.getWidth()/2, mainLayout.getHeight()/2);

    an.setDuration(1000);              
    an.setRepeatCount(0);                     
    an.setFillAfter(false);              // DO NOT keep rotation after animation
    an.setFillEnabled(true);             // Make smooth ending of Animation
    an.setAnimationListener(new AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {}

        @Override
        public void onAnimationRepeat(Animation animation) {}

        @Override
        public void onAnimationEnd(Animation animation) {
                mainLayout.setRotation(180.0f);      // Make instant rotation when Animation is finished
            }
            }); 

mainLayout.startAnimation(an);

mainLayout is a (LinearLayout) field


One line in XML


<View
    android:rotation="45"
    ... />

Rotating view with rotate() will not affect your view's measured size. As result, rotated view be clipped or not fit into the parent layout. This library fixes it though:

https://github.com/rongi/rotate-layout

enter image description here


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()
    }
}

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to view

Empty brackets '[]' appearing when using .where SwiftUI - How do I change the background color of a View? Drop view if exists Difference between View and ViewGroup in Android How to make a view with rounded corners? How to remove all subviews of a view in Swift? How to get a view table query (code) in SQL Server 2008 Management Studio how to add button click event in android studio How to make CREATE OR REPLACE VIEW work in SQL Server? Android findViewById() in Custom View

Examples related to rotation

Setting device orientation in Swift iOS Statically rotate font-awesome icons CSS3 transition on click using pure CSS JS Client-Side Exif Orientation: Rotate and Mirror JPEG Images Rotate an image in image source in html Rotate a div using javascript HTML5 Canvas Rotate Image CSS3 Rotate Animation CSS rotation cross browser with jquery.animate() Rotating a Vector in 3D Space