繁体   English   中英

尝试连续旋转图像时,Android应用程序崩溃

[英]Android App Crashes When Trying to Rotate an Image Continuously

在我的应用程序中创建了一个ImageView并希望连续旋转它,但是当我尝试在手机上运行该应用程序时,它立即崩溃。 这是我的代码:

Java活动文件:

public class FrontPage extends ActionBarActivity {

ImageView iv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_front_page);
    initialize();

    RotateAnimation rotateAnimation1 = new RotateAnimation(0, 360,
            Animation.RELATIVE_TO_SELF, 0.5f,
            Animation.RELATIVE_TO_SELF, 0.5f);
    rotateAnimation1.setInterpolator(new LinearInterpolator());
    rotateAnimation1.setDuration(2000);
    rotateAnimation1.setRepeatCount(Animation.INFINITE);
    iv.startAnimation(rotateAnimation1);
}

private void initialize() {

    iv = (ImageView) findViewById(R.id.motorolaLogo);

}

XML档案:

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        >

        <ImageView
            android:layout_gravity="center_horizontal"
            android:layout_height="150dp"
            android:layout_width="150dp"
            android:layout_marginTop="30dp"
            android:id="@+id/motorolaLogo"
            android:src="@drawable/motologo"
            />

    </RelativeLayout>

您永远不会初始化iv 这是一个Null Pointer Exception

空指针异常是尝试使用空对象。 在您的情况下,您声明ImageView iv,但不要为其分配值。 之后,您尝试使用其方法之一,但由于未正确初始化,因此等效于编写null.startAnimation(rotateAnimation1);

为避免此类错误,您只需要在尝试使用对象的方法之前确保为对象分配了正确的值即可...

* *在讨论后进行了修改您夸大了错误的xml。 代替

 setContentView(R.layout.activity_front_page);

你需要

 setContentView(R.layout.fragment_front_page);

否则,您的Activity将永远找不到正确的对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM