我有一个自定义适配器,我想传递一个 HashMap,其中 Foo 是一个自定义对象
HashMap<String, Foo> foos = new HashMap<String, Foo>();
//populate foos and pass to adapter
fooAdapter = new FooAdapter(getContext(), foos);
我的适配器看起来像这样
public class FooAdapter extends ArrayAdapter<Foo> {
public FooAdapter(Context context, HashMap<String, Foo> foos) {
super(context, R.layout.my_layout, foos);
}
我的问题是将 foos 传递给基本构造函数。我怎样才能让它接受 HashMap 而不是 ArrayList。如果我将其作为 ArrayList 传递,则效果很好,但 HashMap 更适合我的应用程序,因为我使用 Firebase 并且在运行时需要 key 。
最佳答案
使用ArrayList
这是不可能的。
那是因为ArrayAdapter
没有构造函数接受 HashMap
。如果您看到ArrayAdapter source code在第 105 行,您将看到它使用 List<T>
在内部存储其项目。
如果您想使用HashMap
而不是List
只需创建您自己的 HashMapAdapter
通过扩展 BaseAdapter
与源代码中显示的类似,只是替换 List
与 HashMap
并在代码中相应地更新此更改。
关于java - Android Studio 自定义 ArrayAdapter 传递 HashMap 而不是 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59483281/