我正在制作一个数学游戏,并且在按钮单击方法上显示正确/错误答案时遇到了麻烦。基本上,我在我的方程式方法中做了一个 if/else 语句,并且在其中的语句假设做一些事情,比如如果用户输入匹配正确的答案,将 textviews 文本更改为“正确”,否则为“错误”。假设当用户单击按钮时会发生这种情况。
这是我的代码,由于某种原因它没有做任何事情:
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate");
setContentView(R.layout.gamelayout);
int diff = getIntent().getIntExtra(KEY_DIFFICULTY, DIFFICULTY_EASY);
edittext = (EditText) findViewById(R.id.USERentry);
questionLabel = (TextView) findViewById(R.id.question_label);
answerLabel = (TextView) findViewById(R.id.rightwrong_label);
button1 = (Button) findViewById(R.id.keypad_1);
button1.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
// Perform action on clicks
//String buttonText = (String) button.getText();
edittext.setText(edittext.getText() + "1");
//edittext.setText() = edittext.getText() + "1";
}
});
button2 = (Button) findViewById(R.id.keypad_2);
button2.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
edittext.setText(edittext.getText() + "2");
}
});
...some more buttons...
buttonhash = (Button) findViewById(R.id.keypad_hash);
buttonhash.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
answerLabel.getText();
answerLabel.setBackgroundColor(R.color.background_answer);
}
});
getGame(diff);
}
public void Easy12(){
Random rand = new Random();
final int a = (int) rand.nextInt(20)+1;
final int b = (int) rand.nextInt(20)+1;
String aString = Integer.toString(a);
String bString = Integer.toString(b);
String display = aString + " + " + bString + " =";
questionLabel.setText(display);
final int c = a + b;
if(edittext.getText().toString().equals(String.valueOf(c))){
answerLabel.setText(R.string.answer_correct);
answerLabel.setTextColor(R.color.correct_color);
}
else
{
answerLabel.setText(R.string.answer_wrong);
answerLabel.setTextColor(R.color.wrong_color);
//answerLabel.setBackgroundColor(R.color.background_answer);
}
}
没关系,我让它工作了。
基本上我必须在 onCreate() 中通过说 buttonhash.setOnClickListener(this); 来设置 onClickListener;
我还必须为 Game 类实现 OnClickListener。
最后,这导致了一个 onClick(View v) 方法,我可以在其中编写每个按钮的功能。:) 快乐的时光。