2016-09-14 64 views
-3

我目前正在编写一个Android的小游戏,其中一个按钮改变位置。在添加setx和sety函数后,我的应用程序在打开时立即崩溃。Android应用程序崩溃,由于setx和sety功能

这里是我的代码\

JAVA

import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.widget.Button; 

import java.util.Random; 


public class MainActivity extends AppCompatActivity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 

    Random rn = new Random(); 
    float ranx = rn.nextInt(19); 
    float rany = rn.nextInt(10); 
    Button red = (Button) findViewById(R.id.Red); 
    red.setX(ranx); 
    red.setY(rany); 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

} 
} 

XML

<?xml version="1.0" encoding="utf-8"?> 
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:paddingBottom="@dimen/activity_vertical_margin" 
android:paddingLeft="@dimen/activity_horizontal_margin" 
android:paddingRight="@dimen/activity_horizontal_margin" 
android:paddingTop="@dimen/activity_vertical_margin" 
tools:context="com.example.alex.strooper.MainActivity" 
android:columnCount="11" 
android:rowCount="18"> 

<Button 
    android:layout_height="wrap_content" 
    android:layout_width="wrap_content" 
    android:id="@+id/Red" 
    android:text="Red" /> 

</GridLayout> 

这里的错误

09-13 21:49:23.108 28852-28852/? W/art: Failed to open zip archive '/system/framework/qcom.fmradio.jar': I/O Error 

            [ 09-13 21:49:23.108 28852:28852 W/   ] 
            Unable to open '/system/framework/oem-services.jar': No such file or directory 
09-13 21:49:23.108 28852-28852/? W/art: Failed to open zip archive '/system/framework/oem-services.jar': I/O Error 
09-13 21:49:33.304 3807-3807/? W/ResourceType: Failure getting entry for 0x7f0a00ba (t=9 e=186) (error -75) 
的一部分0
+1

在设置布局之前,您正在尝试在布局中查找“View”。 –

+0

谢谢!我应该如何纠正这一点? – gummy714

+0

将'Button'东西移动到'setContentView()'调用之后。 –

回答

0

in onCreate方法,将代码的最后两行移至方法的第一行。

@Override 
protected void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    Random rn = new Random(); 
    float ranx = rn.nextInt(19); 
    float rany = rn.nextInt(10); 
    Button red = (Button) findViewById(R.id.Red); 
    red.setX(ranx); 
    red.setY(rany); 

}