我知道这个问题听起来很奇怪(请随意编辑标题)
,但我想完成的基本上是这样的:
假设我有一个包含 4 个字符串的列表:
ArrayList<String> carList= new ArrayList<>;
carList.add("BMW");
carList.add("GMC");
carList.add("KIA");
carList.add("Honda");
我现在想将列表项中的 3 个打印到 3 个 TextView 中,第四个项目由于某种原因将被排除并且其位置已知。
int excludedIndex = 2; //for example.
for (int i = 0; i < carList.size(); i++) {
if (i != excludedIndex) {
textView_1.setText(carList.get(i)); // here it will put (BMW) in tv1
textView_2.setText(carList.get(??)); // here it should put (GMC) in tv2
textView_3.setText(carList.get(??)); // here it should put (Honda) in tv3
}
}
最佳答案
基本上您是在问:我如何映射列表的元素(由它们的索引标识)到某个文本字段。那句话已经包含了一种可能的解决方案——使用 Map<Integer, TextView>
知道哪个 TextView 应该用于哪个索引。
如:
Map<Integer, TextView> viewsByIndex = ...
for (int i = ... ) {
if (viewsByIndex.containsKey(i)) {
viewsByIndex.get(i).setText(listItem(i));
上面的代码没有编译/检查 - 它更像是灵感/伪代码,展示了如何以一种优雅的方式解决这个问题。
关于java - 如何使用for循环在固定 View 中打印字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48182149/