我有一个自定义适配器,我想传递一个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
。如果在第105行看到ArrayAdapter source code,您将看到它在内部使用List<T>
来存储其项目。
如果要使用HashMap
而不是List
,只需通过扩展HashMapAdapter
来创建自己的BaseAdapter
,类似于源代码中所示的内容,只是用List
替换HashMap
并相应地更新此更改。通过代码。