Lovesome
Lovesome

Reputation: 35

How to choose the best constructor for your Adapter?

Was studying Array adapters, and fonud online, different ways of creating constructs in the Adapter class that extends ArrayAdapter. I got confused but my research took me to

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

After reading, it didn't clear my vagueness. So my question is how do I choose the best constructs from the list provided at the link above if I have :

  1. Two TextViews and an ImageView
  2. Two ImageViews and one TextView for use in the layout

Upvotes: 1

Views: 136

Answers (1)

parliament
parliament

Reputation: 371

I suggest you to take a look BaseAdapter. It s clear and easy to implement. When you start to use it in a few example, you will like it. I will put an example adapter which is implement base adapter. It also includes view holder pattern for performance.

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;

    }
} 

Upvotes: 1

Related Questions