在android中使用charAt(索引)

在android中使用charAt(索引),android,android-studio,Android,Android Studio,我试图将一个字符串分配给不同的按钮,这样字符串中的每个字符都可以使用String.charAt(index)方法分配给每个按钮。比如: private String myString = "34567124"; /*Getting the Views*/ Button bUtton1 = (Button)findViewById(R.id.button1); Button bUtton2 = (Button)findViewById(R.id.button2); Button bUtton3 =

我试图将一个字符串分配给不同的按钮,这样字符串中的每个字符都可以使用String.charAt(index)方法分配给每个按钮。比如:

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

为什么会导致一个错误?

在这种情况下,你可以考虑拆分<代码> MySstring < /C> >(这将把它转换成单个字符串的数组)。然后你可以这样做:

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]);

试试看,让我知道这是否符合你的意图

一个简单的更改将解决您的错误:

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方法将字符串作为参数接收


按钮没有接受字符的
setText
方法
因为它被当作资源ID对待。
它确实接受
字符串
字符序列
的任何实现

您可以使用以下命令,而不是
charAt


尝试将字符转换为字符串(String.valueOf(myString.charAt(0)),但不完全确定。错误消息是什么-请编辑问题并包括错误日志。因为
charAt
返回
char
,并且
setText(char)
不是存在的方法。
String.valueOf(myString.charAt(index))
工作完美字符串[]StringArray的方法charAt(index)不存在,但我在代码中的任何地方都没有使用该方法?我遗漏了什么吗?酷,请投票/接受答案,这样你的问题就可以标记为已回答。快乐编码!String.valueOf(myString.charAt(index))可以完美地工作
charAt()
返回一个字符,并且
setText(char)
不是一个存在的方法。我认为向
char
添加前面的连接仍然可以工作String.valueOf也可以工作。我的解决方案是基于称为自动向上转换的Java概念。如果字符串与任何对象连接,它将自动升级为字符串。
    String myString = "12345678";
    btn.setText(myString.substring(0, 1));
    btn.setText(myString.substring(1, 2));
    btn.setText(myString.substring(2, 3));