问题
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