【问题标题】:How to choose the best constructor for your Adapter?如何为您的适配器选择最佳构造函数?
【发布时间】:2018-10-18 10:48:49
【问题描述】:

正在研究数组适配器,并在网上找到了在扩展 ArrayAdapter 的适配器类中创建构造的不同方法。我很困惑,但我的研究把我带到了

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

阅读后,并没有消除我的模糊性。所以我的问题是,如果我有,如何从上面链接提供的列表中选择最佳构造:

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

【问题讨论】:

  • 实际上你从不使用这些。相反,我们实施自定义适配器以满足我们的需求
  • 最好学习自定义适配器。medium.com/mindorks/…
  • 首先实施任何可行的方法。然后,如果需要,您将能够做得更好。

标签: android android-arrayadapter


【解决方案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;

    }
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-26
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    • 2017-11-21
    • 1970-01-01
    • 2013-01-14
    • 2018-04-24
    相关资源
    最近更新 更多