java Android为按钮分配数组值
我正在做一个类似于徽标测验的问答游戏,我正在尝试创建应用程序所使用的输入样式。它们有随机混合的字母,用户必须找到组成正确答案的字母。到目前为止,我有一个包含按钮和正确答案字母的数组列表,然后我在数组列表中循环,并将按钮文本分配给正确答案数组列表中的字母,但导致强制停止而没有错误。有人知道为什么吗
ArrayList<Character> answer = new ArrayList<Character>();
ArrayList<Button> buttons = new ArrayList<Button>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn1 = (Button) findViewById(R.id.button1);
Button btn2 = (Button) findViewById(R.id.button2);
Button btn3 = (Button) findViewById(R.id.button3);
Button btn4 = (Button) findViewById(R.id.button4);
Button btn5 = (Button) findViewById(R.id.button5);
Button btn6 = (Button) findViewById(R.id.button6);
Button btn7 = (Button) findViewById(R.id.button7);
Button btn8 = (Button) findViewById(R.id.button8);
Button btn9 = (Button) findViewById(R.id.button9);
buttons.add(btn1);
buttons.add(btn2);
buttons.add(btn3);
buttons.add(btn4);
buttons.add(btn5);
buttons.add(btn6);
buttons.add(btn7);
buttons.add(btn8);
buttons.add(btn9);
String testAnswer = "Answer";
//convert to chars and add to arraylist for shuffling
for(char a : testAnswer.toCharArray()){
answer.add(a);
}
Collections.shuffle(answer);
//loop over buttons and letters and assign each button with a letter
for(char a : answer){
for(Button bb : buttons){
bb.setText(String.valueOf(a));
}
}
}
# 1 楼答案
# 2 楼答案
我不明白为什么应用程序强制停止了你给出的代码(看起来不错),但我发现了另一个问题:
此代码不会为每个按钮分配不同的字母,而是为所有按钮分配相同的字母
而是这样做:
如果您不希望字符出现多次,可以在将它们设置为按钮文本后将其从
allowed
中删除# 3 楼答案
你可以做以下几点:
然后用随机字母填充剩下的部分:
假设这是可行的,这应该在一个随机按钮中放入一个“答案”字母,然后用a-z中的其他字母填充其他按钮
p.S:这假设按钮文本默认为“null”,您可以/应该更改这一点