我正在尝试将String分配给不同的Buttons,以便String中的每个字符都使用String.charAt(index)方法分配给每个Button。像:
private String myString = "34567124";
/*Getting the Views*/
Button bUtton1 = (Button)findViewById(R.id.button1);
Button bUtton2 = (Button)findViewById(R.id.button2);
Button bUtton3 = (Button)findViewById(R.id.button3);
//...Rest of the Buttons
/*Setting text for each View*/
bUtton1.setText(myString.charAt(0));
bUtton2.setText(myString.charAt(1));
bUtton3.setText(myString.charAt(2));
...//Rest of the Buttons
为什么会导致错误?
答案 0 :(得分:1)
在这种情况下,您可以考虑拆分myString
(这会将其转换为单字符字符串数组)。然后你可以做这样的事情:
private String myString = "34567124";
//here I am splitting...
private String[] digitsArray = myString.split("");
...
//then you can do this:
bUtton1.setText(digitsArray[0]);
bUtton2.setText(digitsArray[1]);
bUtton3.setText(digitsArray[2]);
尝试一下,让我知道这是否符合你的意图。
答案 1 :(得分:1)
答案 2 :(得分:0)
一个简单的更改将解决您的错误:
private String myString = "34567124";
/*Getting the Views*/
Button bUtton1 = (Button)findViewById(R.id.button1);
Button bUtton2 = (Button)findViewById(R.id.button2);
Button bUtton3 = (Button)findViewById(R.id.button3);
//...Rest of the Buttons
/*Setting text for each View*/
bUtton1.setText(""+myString.charAt(0));
bUtton2.setText(""+myString.charAt(1));
bUtton3.setText(""+myString.charAt(2));
...//Rest of the Buttons
添加先前的连接将解决错误,因为setText方法接收String作为参数。