在Android Studio中切换按钮文本值

时间:2015-03-29 17:19:01

标签: java button android-studio

Hello stackoverflow社区,

我决定开始学习如何在Android Studio中制作Android应用程序,作为第一个项目,我认为制作简单的计算游戏会很有趣。

首先它生成一个随机和,​​例如5 + 5.在总和下面它有4个按钮,我想要生成正确答案和三个错误答案。玩家按下正确或错误答案的按钮,再次生成总和和答案。

enter image description here

    // Generate wrong answers and convert
    int wronganswer1 = (answ1) + 2;
    String wronganswer1string = Integer.toString(wronganswer1);
    int wronganswer2 = (answ1) - 2;
    String wronganswer2string = Integer.toString(wronganswer2);
    int wronganswer3 = (answ1) + 3;
    String wronganswer3string = Integer.toString(wronganswer3);

    //Add Text to the buttons
    Button ansb1 = (Button)findViewById(R.id.answerbutton1);
    ansb1.setText(answer);

    Button ansb2 = (Button)findViewById(R.id.answerbutton2);
    ansb2.setText(wronganswer1string);

    Button ansb3 = (Button)findViewById(R.id.answerbutton3);
    ansb3.setText(wronganswer2string);

    Button ansb4 = (Button)findViewById(R.id.answerbutton4);
    ansb4.setText(wronganswer3string);

这会用一个正确的答案和三个错误的答案填充按钮上的文字。问题是正确答案将始终是顶部的按钮。

我的问题是每次生成新总和时如何切换按钮的值。所以正确的答案不会总是在同一个按钮上。

2 个答案:

答案 0 :(得分:1)

使用数组来保存答案。

String[] ans = new String[4];

int wronganswer1 = (answ1) + 2;
int wronganswer2 = (answ1) - 2;
int wronganswer3 = (answ1) + 3;

ans[0] = Integer.toString(answ1);
ans[1] = Integer.toString(wronganswer1);
ans[2] = Integer.toString(wronganswer2);
ans[3] = Integer.toString(wronganswer3);

Button引用保存到List

List<Button> btns = new ArrayList<Button>(4);

btns.add((Button)findViewById(R.id.answerbutton1));
btns.add((Button)findViewById(R.id.answerbutton2));
btns.add((Button)findViewById(R.id.answerbutton3));
btns.add((Button)findViewById(R.id.answerbutton4));

现在,使用Collections.shuffle()随机化Button s

Collections.shuffle(btns);

并迭代List来设置答案。

for (int i = 0; i < 4; i++) {
    btns.get(i).setText(ans[i]);
}

答案 1 :(得分:0)

你应该在按钮上设置一个随机的字符串,这样字符串就可以拦截计算,所以如果(正确答案)是#转到按钮#,错误答案是# - #转到按钮#