Skip to content Skip to sidebar Skip to footer

Rotate An Imagebutton On Orientation Change

I have an image button that I want to rotate when the orientation of the device changes. How can I rotate the image with some animation or transition ?

Solution 1:

try this code snippet.

rotate.xml

<?xml version="1.0" encoding="utf-8"?><setxmlns:android="http://schemas.android.com/apk/res/android"><rotateandroid:fromDegrees="0"android:toDegrees="360"android:pivotX="50%"android:pivotY="50%"android:repeatCount="0"android:duration="2000" /></set>

rorate_anticlockwise.xml

<?xml version="1.0" encoding="utf-8"?><setxmlns:android="http://schemas.android.com/apk/res/android"><rotateandroid:fromDegrees="0"android:toDegrees="-360"android:pivotX="50%"android:pivotY="50%"android:repeatCount="0"android:duration="2000" /></set>

for checking orientation of the phone use this code

int orientation =this.getResources().getConfiguration().orientation;

the complete code for MainActivity.java is

publicclassMainActivityextendsActivity{

/* (non-Javadoc)
 * @see android.app.Activity#onCreate(android.os.Bundle)
 */
ImageButton image_btn;

Animation ranim_clockwise, ranim_anticlockwise;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stubsuper.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    image_btn= (ImageButton)findViewById(R.id.imageButton1);
    ranim_clockwise = AnimationUtils.loadAnimation(this,R.anim.rotate);
    ranim_anticlockwise = AnimationUtils.loadAnimation(this,R.anim.rotate_anticlock);
    intorientation=this.getResources().getConfiguration().orientation;
    if(orientation==1){ // portrait mode
        image_btn.setAnimation(ranim_clockwise);
    }
    if(orientation==2){  //landscape mode
        image_btn.setAnimation(ranim_anticlockwise);
    }

}

}

hopefully it will help you.

Post a Comment for "Rotate An Imagebutton On Orientation Change"