默认情况下,ArrayAdapter 将为您的ArrayList 中的每个数组项创建视图。要自定义 ArrayAdapter 如何为您的数据创建视图,您需要扩展它并覆盖其 getView() 方法并为每个项目使用不同的布局,就像这样
注意: 我假设 Music 是具有这 3 个字符串的类,并且您创建了一个名为 unique_layout.xml 的新布局,它只有一个 TextView显示一个你这些字符串。
public class CustomArrayAdapter extends ArrayAdapter<Music> {
public CustomArrayAdapter(Context context, ArrayList<Music> musicList) {
super(context, 0, users);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Music music = getItem(position);
// Here use that new layout that you created
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.unique_layout, parent, false);
}
// Assign text to the TextView from that new layout
TextView category = (TextView) convertView.findViewById(R.id.category);
category.setText(music.category);
return convertView;
}
}
更新:从 ArrayList 中删除重复项
注意:以下方法会删除重复项并将结果列表放入新的ArrayList<String>,您可以将其用作ArrayAdapter 的来源。所以你现在不必扩展ArrayAdapter。
从ArrayList中删除重复项的常用方法有3种
- 手动操作(祝你好运)
- 使用
Streams (仅适用于 API 24:牛轧糖及更高版本)
- 使用
LinkedHashSet (从 API 1 开始可用)
假设您有如下定义的数组列表
ArrayList<Music> musicList = new ArrayList<>();
ArrayList<String> categoryList = new ArrayList<>();
musicList.add(new Music("song1", "category1", "artist1"));
musicList.add(new Music("song2", "category2", "artist2"));
musicList.add(new Music("song3", "category3", "artist3"));
musicList.add(new Music("song4", "category2", "artist4"));
musicList.add(new Music("song5", "category1", "artist1"));
musicList.add(new Music("song6", "category4", "artist5"));
musicList.add(new Music("song7", "category3", "artist2"));
选项 2:使用Streams
我在这里所做的是使用map() 方法仅提取category 字段并使用distinct() 方法删除重复项,然后最终将所有这些修改收集到categoryList 中。如果你需要提取独特的艺术家,只需将music.category更改为music.artist
EZ!
注意: 在 map() 方法之后,我们现在正在处理字符串数组,因此 distinct() 使用 equals() 和 hashCode() 方法987654349@ 类查找和删除重复项。如果您在 musicList 上直接使用 distinct(),它是 Music 类的数组,那么您的 Music 类应该覆盖并提供 equals() 和 hashCode() 方法的实现。
阅读更多关于他们的信息here 或here
categoryList = musicList.stream()
.map((music)-> music.category)
.distinct()
.collect(Collectors.toCollection(ArrayList::new));
Log.d("CATEGORY LIST" , categoryList.toString())
//LOG Output
CATEGORY LIST: [category1, category2, category3, category4]
选项 3:使用LinkedHashSet
这个方法比较简单。和之前一样,首先提取category 字段并将它们存储到categoryList。创建LinkedHashSet 将自动删除重复值,就像使用流时的distinct() 方法一样。之后只需清除 categoryList 并使用哈希集中的唯一值对其进行更新。
musicList.forEach((music) -> {
categoryList.add(music.category);
});
LinkedHashSet<String> uniqueCategoryHashSet = new LinkedHashSet(categoryList);
categoryList.clear();
categoryList.addAll(uniqueCategoryHashSet);
Log.d("CATEGORY LIST" , categoryList.toString())
//LOG Output
CATEGORY LIST: [category1, category2, category3, category4]
现在我绝不会将 选项 3 标记为有效的解决方案。如果由于 API 限制而无法使用流,也许您可以手动执行此操作会更好。但这可以完成工作。