Xamarin中ArrayAdapter无法适配int[]数组问题求助
解决思路:在ListView中用ArrayAdapter展示int[]数组
别担心,这个问题其实有好几种简单易行的解决方式,我给你梳理几个最常用的:
方案1:把int[]直接转换成String[](最贴合你现有代码场景)
既然你已经在使用for循环,刚好可以利用这个循环把每个int元素转成字符串:
int[] intArray = {1, 2, 3, 4, 5}; String[] stringArray = new String[intArray.length]; // 就在你现有的for循环里完成转换 for (int i = 0; i < intArray.length; i++) { stringArray[i] = String.valueOf(intArray[i]); } // 把转换后的String数组传给ArrayAdapter ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, stringArray); listView.setAdapter(adapter);
这个方法完全适配你提到的“for循环内有int变量i”的情况,几乎不需要额外改动现有逻辑。
方案2:使用泛型ArrayAdapter(更简洁)
其实ArrayAdapter支持泛型,你没必要非要转成String数组——ArrayAdapter默认会调用对象的toString()方法,而Integer的toString()刚好就是它的字符串形式:
int[] intArray = {1, 2, 3, 4, 5}; // 把int[]转成Integer类型的List(Java 8+可用stream简化) List<Integer> integerList = Arrays.stream(intArray).boxed().collect(Collectors.toList()); // 直接用Integer类型的ArrayAdapter ArrayAdapter<Integer> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, integerList); listView.setAdapter(adapter);
如果你的Java版本低于8,也可以用for循环把int数组的元素逐个加到ArrayList里,效果是一样的。
方案3:自定义ArrayAdapter(灵活度最高)
如果之后你需要对列表项做更多自定义(比如修改样式、添加额外逻辑),可以自己写个继承自ArrayAdapter的类,重写getView方法来处理int类型:
public class IntArrayAdapter extends ArrayAdapter<Integer> { private int[] intData; public IntArrayAdapter(Context context, int resource, int[] data) { super(context, resource); this.intData = data; } @Override public int getCount() { return intData.length; } @Override public Integer getItem(int position) { return intData[position]; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(android.R.layout.simple_list_item_1, parent, false); } TextView textView = convertView.findViewById(android.R.id.text1); textView.setText(String.valueOf(intData[position])); return convertView; } }
使用时直接传入int数组即可:
IntArrayAdapter adapter = new IntArrayAdapter(this, android.R.layout.simple_list_item_1, intArray); listView.setAdapter(adapter);
这几个方案里,方案1最适合你当前的代码情况,直接在现有for循环里加转换逻辑就行,成本最低。
内容的提问来源于stack exchange,提问作者Arfmann
相关产品推荐
相关产品推荐

