我的代码运行良好,但只有一次。当===>时我需要重复ok = (Button) findViewById(R.id.btnOk);
点击。
这是代码
String questionNumber = "";
EditText answer;
Button ok;
TextView question;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
answer = (EditText) findViewById(R.id.answer);
ok = (Button) findViewById(R.id.btnOk);
question = (TextView) findViewById(R.id.TextViewQuestion);
Random random = new Random();
questionNumber = String.format("%04d",random.nextInt(10000));
question.setText(questionNumber);
ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (answer.getText().toString().equals(questionNumber)) {
Toast.makeText(getBaseContext(),"Input True", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Input Wrong", Toast.LENGTH_LONG).show();
}
}
});
}
}
答案 0 :(得分:1)
这样做..
String questionNumber = "";
EditText answer;
Button ok;
TextView question;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
answer = (EditText) findViewById(R.id.answer);
ok = (Button) findViewById(R.id.btnOk);
question = (TextView) findViewById(R.id.TextViewQuestion);
getRandomQuestion();
ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (answer.getText().toString().equals(questionNumber)) {
Toast.makeText(getBaseContext(),"Input True", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Input Wrong", Toast.LENGTH_LONG).show();
}
getRandomQuestion();
}
});
}
private void getRandomQuestion() {
Random random = new Random();
questionNumber = String.format("%04d",random.nextInt(10000));
question.setText(questionNumber);
}
请记住将getRandomQuestion()放在检查器下面,因为如果你把它放在上面那么我相信它总会显示输入错误的吐司,除非第一个随机数与第二个随机数相同。
例如...... 你在onCreate中生成了一个随机问题,让我们说它是1 .. 然后你在editText中加1,所以你假设它应该显示输入True,对吗?但是如果你把getRandomQuestion放在检查器之上......会发生什么,你会再次生成一个随机问题然后它会是2 ..
然后,在你的检查员......你的答案是1然后问题是2 ..所以它不会是平等的。
答案 1 :(得分:0)
这是你的解决方案 把这个
Random random = new Random();
questionNumber = String.format("%04d",random.nextInt(10000));
question.setText(questionNumber);
在按钮列表器中 修改强>
ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (answer.getText().toString().equals(questionNumber)) {
Toast.makeText(getBaseContext(),"Input True", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Input Wrong", Toast.LENGTH_LONG).show();
}
Random random = new Random();
questionNumber = String.format("%04d",random.nextInt(10000));
question.setText(questionNumber);
}
});