2016-09-14 6 views
-3

私は現在、ボタンが位置を変えるアンドロイド用の小さなゲームを書いています。 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) 
の一部ですonCreateメソッド内の0
+1

あなたはレイアウトを設定する前に、あなたのレイアウトで 'View'を探しています。 –

+0

ありがとう!これをどのように修正すればよいですか? – gummy714

+0

'setContentView()'コールの後に 'Button'を移動します。 –

答えて

0

、コードの最後の2行を最初のメソッドに移動します。

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

} 
関連する問題