Java 如何在循环中将字符串的每个字符设置为不同的TextView
我已经宣布了所有的目标,并阅读了一些线索。后来,我试图建立一个阵列,但没有成功。此外,我担心的是,当我将所有文本视图放在一个数组中时,它们在应用程序的整个设计中不再起作用 我认为我的最后一次尝试是最接近解决方案的 示例(但未键入imgBeer 5次):Java 如何在循环中将字符串的每个字符设置为不同的TextView,java,android,for-loop,char,textview,Java,Android,For Loop,Char,Textview,我已经宣布了所有的目标,并阅读了一些线索。后来,我试图建立一个阵列,但没有成功。此外,我担心的是,当我将所有文本视图放在一个数组中时,它们在应用程序的整个设计中不再起作用 我认为我的最后一次尝试是最接近解决方案的 示例(但未键入imgBeer 5次): if(calc.getBeerCount()I figure id out finally=) 在Fragment类中,我实例化了一个ArrayList&设置TextView文本的方法: private ArrayList<TextView
if(calc.getBeerCount()I figure id out finally=)
在Fragment类中,我实例化了一个ArrayList&设置TextView文本的方法:
private ArrayList<TextView> test = new ArrayList<>();
public void showConsumption(){
if(calc.getBeerCount() < 100000) {
String convert = Integer.toString(calc.getBeerCount());
for (int i = 0; i < convert.length(); i++) {
test.get(i).setText(Character.toString(convert.charAt(i)));
}
}else{
txtAlcLvl.setText("For sure! Do you coun't annually?");
}
}
}
无论如何,谢谢你的帮助,显然我的问题问得还不够准确。那么你的循环次数可能会达到100000次?你有100000个文本浏览量吗?!?你只需要循环convert.length()
@Mark Kenn,你是对的,这不是我想要做的。我更改了部分并将其标记为//edited。我只想将getBeerCount()中int的所有5个字符放在单独的文本视图中。如果您想使用这样的动态文本视图名称,您需要查看Context.getResources().getIdentifier()。此外,如果您计划动态添加这些文本视图并将它们放在滚动视图中(这是我能想象的许多文本视图的唯一方式),您最好查看RecyclerView和适配器。我已经在xml中设置了所有文本视图,现在不能更改它。我有点困惑,难道没有一种方法可以通过递增的数字来处理多个文本视图吗?imgBeer+i或类似的东西?
if(calc.getBeerCount()<100000){
String convert = Integer.toString(calc.getBeerCount());
for(int i = 0; i < convert.lenght(); i++){ //edited
String test = "imgBeer" + i;
test.setText(convert.charAt(i));
}
}else{
txtAlcLvl.setText("For sure! Do you coun't annually?");
}
if(calc.getBeerCount()<100000){
String convert = Integer.toString(calc.getBeerCount());
for(int i = 0; i < convert.lenght(); i++){ //edited
((TextView)findViewById(textViewIds[i])).setText(convert.charAt(i));
}
}else{
txtAlcLvl.setText("For sure! Do you coun't annually?");
}
private ArrayList<TextView> test = new ArrayList<>();
public void showConsumption(){
if(calc.getBeerCount() < 100000) {
String convert = Integer.toString(calc.getBeerCount());
for (int i = 0; i < convert.length(); i++) {
test.get(i).setText(Character.toString(convert.charAt(i)));
}
}else{
txtAlcLvl.setText("For sure! Do you coun't annually?");
}
}
}
TextView imgBeer1 = (TextView) v.findViewById(R.id.imgBeer1);
TextView imgBeer2 = (TextView) v.findViewById(R.id.imgBeer2);
TextView imgBeer3 = (TextView) v.findViewById(R.id.imgBeer3);
TextView imgBeer4 = (TextView) v.findViewById(R.id.imgBeer4);
TextView imgBeer5 = (TextView) v.findViewById(R.id.imgBeer5);
test.add(imgBeer1);
test.add(imgBeer2);
test.add(imgBeer3);
test.add(imgBeer4);
test.add(imgBeer5);