Rotate an ImageButton on orientation change

2019-08-07 14:21发布

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 ?

1条回答
SAY GOODBYE
2楼-- · 2019-08-07 14:47

try this code snippet.

rotate.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<rotate

android: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"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<rotate
android: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

public class MainActivity  extends Activity{

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

Animation ranim_clockwise, ranim_anticlockwise;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.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);
    int orientation =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.

查看更多
登录 后发表回答