如何使用ListView实现自定义适配器?

时间:2019-05-28 14:39:45

标签: android android-listadapter

嗨,当我需要解析列表视图中的数组时,我正在使用一个android应用程序。我已经为此创建了一个自定义适配器,但是我在这里缺少了一些东西。

public class IndustryAdapter extends ArrayAdapter<Industry> {
    Context context;
    int resource;
    public IndustryAdapter(Context context, ArrayList<Industry> industries) {
        super(context, industries);
    }

    @Override
    public View getView(View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
        }
        TextView tvName = (TextView)convertView.findViewById(R.id.tvName);
        TextView tvDescription = (TextView)convertView.findViewById(R.id.tvDescription);

        return convertView;
    }


}

On the super(context, industries) is showing an error for industries:

required: 'int'
error: incompatible types: ArrayList<Industry> cannot be converted to int

2 个答案:

答案 0 :(得分:1)

使用基本适配器为您的列表创建自定义适配器

class CustomAdapter extends BaseAdapter {
   private ArrayList<Industry> industries;
    private Context context;

    public CustomAdapter(ArrayList<Industry> industries, Context context) {
        this.industries = industries;
        this.context = context;
    }

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

    @Override
    public Object getItem(int position) {
        return industries.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.your_layout, parent, false);
        }
        TextView tvName = (TextView)convertView.findViewById(R.id.tvName);
        TextView tvDescription = (TextView)convertView.findViewById(R.id.tvDescription);

        return convertView;
    }
}

答案 1 :(得分:0)

您应该只更改您的超级构造函数调用。因为它收到您将要膨胀的布局资源。像这样:

public IndustryAdapter(Context context, ArrayList<Industry> industries) {
            super(context, android.R.layout.simple_list_item_1);
        }