public class MainActivity extends Activity {
int minValue;
int maxValue;
int rndNum;
TextView rndNumText = (TextView) findViewById(R.id.Number);
EditText MinVal = (EditText) findViewById(R.id.editTextMin);
EditText MaxVal = (EditText) findViewById(R.id.editTextMax);
Button btnRandom = (Button) findViewById(R.id.Randomize);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnRandom.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
minValue = Integer.parseInt(MinVal.getText().toString());
maxValue = Integer.parseInt(MaxVal.getText().toString());
Random r = new Random();
rndNum = r.nextInt(maxValue - minValue + 1) + minValue;
rndNumText.setText(Integer.toString(rndNum));
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
我没有错误,所以eclipse允许我运行程序,但是当它即将执行时,它会给我一个错误,说“不幸的是,程序名称已停止。”
我做错了什么?我非常感谢您的见解。
答案 0 :(得分:1)
完成这些
的所有初始化TextView rndNumText = (TextView) findViewById(R.id.Number);
EditText MinVal = (EditText) findViewById(R.id.editTextMin);
EditText MaxVal = (EditText) findViewById(R.id.editTextMax);
Button btnRandom = (Button) findViewById(R.id.Randomize);
onCreate
之后的setContextView()
内的,否则视图尚未初始化并被赋予了ID。