java Android应用程序启动前崩溃
显示两个随机数并计算奇数和偶数圈数。当其中一个达到100时,应用程序停止
这是我的java应用程序文件
public class Board_Play1 extends Activity {
int d=0,a=0,b=0,turn=2;
Random random = new Random();
EditText diceno = (EditText) findViewById(R.id.editText1);
EditText p1 = (EditText) findViewById(R.id.editText2);
EditText p2 = (EditText) findViewById(R.id.editText3);
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.board_play1);
diceno.setText(String.valueOf(d));
p1.setText(String.valueOf(a));
p2.setText(String.valueOf(b));
while(a!=100 && b!=100)
{
if(turn%2==0)
{
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
d=random.nextInt(6)+1;
EditText diceno = (EditText) findViewById(R.id.editText1);
diceno.setText(String.valueOf(d));
}
});
}
else
{
d=random.nextInt(6)+1;
diceno.setText(String.valueOf(d));
}
if(turn%2==0)
a+=d;
else
b+=d;
if(a>100)
a-=d;
if(b>100)
b-=d;
p1.setText(String.valueOf(a));
p2.setText(String.valueOf(b));
turn++;
}
a=0;b=0;
}
}
它不会打开并给出一个错误,即Unfortunately your app has stopped
。为什么会这样?我能换什么
# 1 楼答案
在
setContentView
之后onCreate
内移动所有这些内容findViewById
在当前视图层次结构中查找视图。您需要首先将布局的内容设置为活动,然后使用findViewById
初始化VIE此外,无需在按钮onClick中重新初始化editText。用同样的方法处理下面的问题
也移动这个
在while循环之前。不需要每次都初始化