将转换后的List <string>加载到listview

时间:2018-04-05 15:48:23

标签: android list listview

我的android应用程序中有一个填充List(ServicesList) - 类型为String,自定义类(ServiceRecord.java),自定义适配器()和自定义列表视图(lvS)。

我已经能够通过以下代码将List变量转换为自定义列表:

    List<ServiceRecord> objectList = (List)servicesList;
    ServicesCustomAdapter adapter = new ServicesCustomAdapter(this, objectList);
    lvS.setAdapter(adapter);  

我想将转换后的列表设置为listview但是我收到错误'java.lang.classexception:java.lang.String无法强制转换为app.services.net.ServiceRecord'。有人可以告诉我如何去做。

我的自定义类如下:

public class ServiceRecord {
    private String service;


    public String getService() {
        return service;
    }
    public void setService(String service) {
        this.service = service;
    }

}

我的自定义适配器:

public class ServicesCustomAdapter extends ArrayAdapter<ServiceRecord>{
    private List<ServiceRecord> items;

    public ServicesCustomAdapter(Context context, List<ServiceRecord> items) {
        super(context, R.layout.list_service, items);
        this.items = items;
    }

    @Override
    public int getCount() {
        return items.size();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;

        if(v == null) {
            LayoutInflater li = LayoutInflater.from(getContext());
            v = li.inflate(R.layout.list_service, null);            
        }

        ServiceRecord bbs = items.get(position);

        if(bbs != null) {
            //TextView un = (TextView)v.findViewById(R.id.list);
            TextView tvservice = (TextView)v.findViewById(R.id.tvservice);


            if(tvservice != null) tvservice.setText(bbs.getService());

        }

        return v;
    }

}

1 个答案:

答案 0 :(得分:3)

您必须创建一个包含List类对象的ServiceRecord。请尝试下面的代码。

 List<ServiceRecord> objectList = new ArrayList<>();
    for (String item: servicesList){
        ServiceRecord sr=new ServiceRecord();
        sr.setService(item);
        objectList.add(sr);
    }
    ServicesCustomAdapter adapter = new ServicesCustomAdapter(this, objectList);
    lvS.setAdapter(adapter);

PS:虽然您的ServiceRecord课程只有一个属性。那么为什么不使用List<String>来完成列表适配器。