Rotate an ImageButton on orientation change

与世无争的帅哥 提交于 2019-12-13 00:21:08

问题


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:


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.



来源:https://stackoverflow.com/questions/23677870/rotate-an-imagebutton-on-orientation-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!