2016-09-14 68 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); 

}