android - 在方向更改时旋转 ImageButton

标签 android android-orientation image-rotation android-imagebutton

我有一个图像按钮,我想在设备方向改变时旋转它。如何使用一些动画或过渡来旋转图像?

最佳答案

试试这个代码 fragment 。

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>

要检查手机的方向,请使用此代码

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

MainActivity.java的完整代码是

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

}

希望对你有帮助。

关于android - 在方向更改时旋转 ImageButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23677870/

相关文章:

javascript - 旋转包含的图像后,div 高度设置不正确

java - Android - 如何知道设备何时平地?

android - 将多个对象传递给 onRetainNonConfigurationInstance

python - 翻转图像 Python

java - 如何在我的应用上使用 Admob Live 广告?

android - fragment 的 savedInstanceState 是否与父 Activity 的 savedInstanceState 共享?

jquery - 连续旋转图像

android - Android Studio 更新后突然我的 Java 和 Xml 文件改变了

android - 无法在 Eclipse 中找到混淆的 Firebase 类

java - 我应该将应用程序子类对象保留为成员变量还是局部变量?