java - 使用 List<type> 而不是 ArrayList<Hashmap<String,String>> 进行 ListView

标签 java android arraylist

我有一个对象:

private ArrayList<HashMap<String, String>> customerDataList;

我用从网络服务调用中检索到的数据填充其中。下面是在循环中迭代检索到的 json 数据:

HashMap<String, String> customer = new HashMap<>();
//snip
customer.put("CustomerName", customerName);
//snip
customerDataList.add(customer);
//rinse and repeat

然后我在 Activity 的 ListView 中显示它:

ListAdapter adapter = new SimpleAdapter(Activity.this, customerDataList,
                R.layout.list_item, new String[] {"CustomerName"}, new int[] { R.id.customerName });
setListAdapter(adapter);

但是我想知道是否有一种方法可以使用列表来代替。

我创建了我的客户类,像这样创建了一个列表:

private List<Customer> customerList;

但是,在设置 ListAdapter 时,我不确定要放什么。我用 customerList 替换了 customerDataList,但我收到错误。

编辑:错误是

SimpleAdapter() in SimpleAdapter cannot be applied to:
Expected data: java.util.Map<java.lang.String.?>>
Actual arguments: customerList <Customer>

编辑:我的类结构

private class Customer
{
    private int customerID;
    private String customerName;
    private String customerLocation;
    private String runningTime;
    private double distance;
}

最佳答案

如果您想要使用自定义对象列表,您需要使用另一个适配器,例如数组适配器:

List<Customer> customerList = null;
ArrayAdapter<Customer> customerAdapter = new ArrayAdapter<Customer>(this,
        R.layout.list_item, customerList);

现在,由于 ArrayAdapter 期望字符串来自您的自定义对象,因此在您的类中覆盖 toString 方法:

class Customer {
    String customerName;

    @Override
    public String toString() {
        return customerName;
    }
}

如果您的客户类有多个字段需要在您的适配器中使用,您将需要一个自定义适配器,如下所示:

// Turns out that when the layout is not a TextView, you need to provide the id
// of the TextView the adapter can bind to
ArrayAdapter<Customer> customerAdapter = new ArrayAdapter<Customer>(this,
        R.layout.list_item, R.id.customer_name, customerList) {
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);

        TextView name = view.findViewById(R.id.customer_name);
        TextView surname = view.findViewById(R.id.customer_surname);

        name.setText(getItem(position).customerName);
        surname.setText(getItem(position).customerSurname);

        return view;
    }
};

你可以google一下自定义适配器的一些性能调整。

关于java - 使用 List<type> 而不是 ArrayList<Hashmap<String,String>> 进行 ListView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27880112/

相关文章:

android - 如何访问我的 AndroidManifest.xml 文件中的 BuildConfig 值?

java - MP3 文件无法使用 jl 库播放

java - "garbage collection rate"是什么意思,它能提供什么好处?

android - 在另一个线程中设置套接字连接

Java:按降序对 ArrayList<Object> 进行排序

java - 如何将创建的ArrayList存储在内存中,这样它就不会在每次应用程序启动时创建?

Java Arraylist<Object> 想要合并具有相同属性值的对象

java - 请求在 postman 中工作正常,但在 OkHTTP 中收到 403

java - 如何获取Infinispan缓存中的数据大小,替代ehcache的calculateInMemorySize?

c# - Xamarin Android 客户端将 JSON 发布到 Node JS Web 服务