剛剛開始學習android程序的開發,參照教材自行寫了一個“幸運8”的游戲,可一運行手機就會彈出“幸運8已停止運行”的提示,請各位大神教教小弟代碼哪裡出錯了···感激萬分
package com.luck8;
import com.luck8.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Luck8Activity extends Activity {
/** Called when the activity is first created. */
Button button1=(Button)findViewById(R.id.button2);
Button button2=(Button)findViewById(R.id.button1);
TextView text1=(TextView)findViewById(R.id.textView1);
TextView text2=(TextView)findViewById(R.id.textView2);
TextView text3=(TextView)findViewById(R.id.textView3);
Thread t;
int x,y,z;
boolean RUN =false;
//----------------以上是獲取各個按鈕和textView的實例
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button1.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
start(); //開始按鈕監聽事件
}
});
button2.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
stop(); //停止按鈕監聽事件
}
});
}
protected void stop() {
// TODO Auto-generated method stub
RUN = false;
t = null; //停止方法
}
protected void start() {
// TODO Auto-generated method stub
RUN = true;
t = new Thread();
t.start(); //開始方法
}
@SuppressWarnings("static-access")
public void run(){ //線程的run方法
while(RUN){
x = (int)(Math.random()*10);
y = (int)(Math.random()*10);
z = (int)(Math.random()*10);
text1.setText(String.valueOf(x));
text2.setText(String.valueOf(x));
text3.setText(String.valueOf(x));
try{
t.sleep(1000); //線程等待
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
控件的初始化要放在onCreate()中
Button button1=(Button)findViewById(R.id.button2);
Button button2=(Button)findViewById(R.id.button1);
TextView text1=(TextView)findViewById(R.id.textView1);
TextView text2=(TextView)findViewById(R.id.textView2);
TextView text3=(TextView)findViewById(R.id.textView3);
改為
Button button1;
Button button2;
TextView text1;
TextView text2;
TextView text3;
然後在setContentView(R.layout.main);下面寫:
button1=(Button)findViewById(R.id.button2);
button2=(Button)findViewById(R.id.button1);
text1=(TextView)findViewById(R.id.textView1);
text2=(TextView)findViewById(R.id.textView2);
text3=(TextView)findViewById(R.id.textView3);
最後,別忘了在Manifest中注冊你的Luck8Activity