如何为您的适配器选择最佳的构造函数?

时间:2018-10-18 10:48:49

标签: android android-arrayadapter

正在研究Array适配器,并且在线上喜欢使用在扩展ArrayAdapter的Adapter类中创建构造的不同方法。我很困惑,但是研究使我进入了

https://developer.android.com/reference/android/widget/ArrayAdapter.html#ArrayAdapter(android.content.Context,%20int)

阅读后,我的含糊不清。所以我的问题是,如果我有以下方法,如何从上面链接提供的列表中选择最佳结构:

  1. 两个TextViews和一个ImageView
  2. 用于布局的两个ImageViews和一个TextView

1 个答案:

答案 0 :(得分:1)

我建议您看一下BaseAdapter。它很容易实现。在几个示例中开始使用它时,您会喜欢它。我将提供一个示例适配器,它是工具基本适配器。它还包括用于性能的视图持有人模式。

public class CustomListViewAdapter extends BaseAdapter {

    private Context context;
    private List<Object> objectList;

    public CustomListViewAdapter(Context context, List<Object> objectList) {
        this.context = context;
        this.objectList = objectList;
    }

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

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        Object object = getItem(position);
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.custom_list_row, null);

            holder = new ViewHolder();
            holder.textProperty = convertView.findViewById(R.id.text_property);
            holder.imageProperty = convertView.findViewById(R.id.image_property);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.textProperty.setText(object.getDisplayName());
        holder.imageProperty.setBackgroundResource(object.checkForSomething() ? R.mipmap.first_image:R.mipmap.second_image);
        return convertView;
    }

    static class ViewHolder{
        private TextView textProperty;
        private ImageView imageProperty;

    }
}