所以我们正在开发一个测验游戏/应用程序,我们只有一件事有问题。 我们有4个按钮用于可能的答案,其中只有一个是正确的(obviusly)。它们是带有文本的常规按钮,而不是无线电按钮。问题在于,为了避免为每个问题创建一个活动,我们希望将按钮保留在一个活动中,并且当按下"正确答案时#34;更改按钮功能是不同的。例如按钮1,2,3都将播放器发送给屏幕,而按钮4则是正确的。然后它应该更改按钮上显示的文本并更改所有按钮'功能,以便1,3,4现在是"游戏超过按钮" 2是正确的。我们尝试过if语句和整数以及布尔值无济于事。任何可以帮助我们的提示或解决方案? 感谢
答案 0 :(得分:1)
鉴于你当前的设置,我会让每个按钮的onClick调用validateCorrectAnswer(int buttonNumber)
这样的方法然后从那里你做验证。因此,对于button1,您可以拨打validateCorrectAnswer(1)
。
从validateCorrectAnswer(...)
你有一系列正确答案,所以它可能类似于int[] correctAnswers = {4, 2, 3, 4, 1, 3, 2, 1, ...};
,并且根据你所检查的问题而定。因此,假设您在问题3中检查correctAnswers[2] == buttonNumber
。
因此,要在活动商店中进一步简化它们在全局变量中的当前问题,例如private int currentQuestion = 0
,然后在每个问题之后增加该数字。
所以最后的方法是这样的:
void validateCorrectAnswer(int buttonNumber) {
if (correctAnswer[currentQuestion] == buttonNumber) {
currentQuestion++;
// correct answer, cool move on
} else {
// wrong answer, game over
}
}
答案 1 :(得分:0)
在您的问题类中,您可以设置文本/按钮ID的答案,如果按钮文本/ ID与您的答案相同,则选中按钮单击。
另外,请参阅butterknife的这个例子:
//Specify multiple IDs in a single binding for common event handling.
@OnClick({ R.id.door1, R.id.door2, R.id.door3 })
public void pickDoor(DoorView door) {
if (door.hasPrizeBehind()) {
Toast.makeText(this, "You win!", LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Try again", LENGTH_SHORT).show();
}
}
答案 2 :(得分:0)
您可以使用4个按钮的 setTag(tagValue)和 getTag(tagValue)方法。
1 - 正确
0 - 错误
然后根据给出的答案切换tagValues。
@Override
public void onClick(View view) {
int answer = 0;
if(view instanceof Button) {
answer = (int) ((Button)view).getTag();
}
if(answer == 1) {
//true answer
refreshButtons();
} else {
//game over
}
Log.d("TAG", "a: "+answer);
}
public void refreshButtons () {
questionNr ++;
Log.d("TAG", "q: "+questionNr);
setAnswers(questionNr);
}
public void setAnswers (int question) {
switch (question){
case 1: // Second question
v1.setTag(0);//wrong
v2.setTag(1);//correct
v3.setTag(0);//wrong
v4.setTag(0);//wrong
break;
case 2:// Third question
v1.setTag(0);//wrong
v2.setTag(0);//wrong
v3.setTag(1);//correct
v4.setTag(0);//wrong
break;
case 3:// Forth question
v1.setTag(0);//wrong
v2.setTag(0);//wrong
v3.setTag(0);//wrong
v4.setTag(1);//correct
break;
}
}
您还可以在同一 setAnswer()方法
中设置其他视图的文本onCreate()方法可能是这样的:
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//here you setup the answers for the first question
v1 = (Button) findViewById(R.id.button1);
v1.setOnClickListener(this);
v1.setTag(1);
v2 = (Button) findViewById(R.id.button2);
v2.setOnClickListener(this);
v2.setTag(0);
v3 = (Button) findViewById(R.id.button3);
v3.setOnClickListener(this);
v3.setTag(0);
v4 = (Button) findViewById(R.id.button4);
v4.setOnClickListener(this);
v4.setTag(0);