ListView view recycling with CustomAdapter

后端 未结 1 915
有刺的猬
有刺的猬 2020-12-18 16:12

I\'m inflating two different layouts for a ListView. Everything works until I start scrolling down where the 2 different layouts begin being applied randomly. I\'ve followed

相关标签:
1条回答
  • 2020-12-18 16:36

    You need to override the following methods:

    https://developer.android.com/reference/android/widget/Adapter.html#getViewTypeCount() https://developer.android.com/reference/android/widget/Adapter.html#getItemViewType(int)

    These will let the listview know how many types of views you have and which position is of which type. This will prevent the listview from passing the incorrect convertview type into your getView method.

    EDIT:

    Let's take a step back. The reason you are seeing this problem is ListView is passing the incorrect convertView into your getView() method. The default getViewTypeCount() returns 1, so listView assumes you only have one view type. You are using two types of views for your rows: R.layout.list_offer_group, and R.layout.list_offer. When convertView is not null, you are not checking to see which layout convertView is -- in some cases it will be the incorrect layout.

    To remedy this:

    override getViewTypeCount to return 2, since you have two different types. Override getItemViewType to use your group/non-group logic

    public int getItemViewType(int position) {
      if (nameCompare.equalsIgnoreCase(offers[position].getCustomerName())) {
        return 0;
      } else {
        return 1;
      }
    }
    

    This is now returning 0 for groups and 1 for non-groups. Then we can use getItemViewType() in getView to determine which view we are using, so:

            if (nameCompare.equalsIgnoreCase(offers[position].getCustomerName())) {
                convertView = inflater.inflate(R.layout.list_offer_group, null);
            }
            else {
                nameCompare = offers[position].getCustomerName();
                convertView = inflater.inflate(R.layout.list_offer, null);
            }
    

    becomes:

            if (getItemViewType(position) == 0) {
                convertView = inflater.inflate(R.layout.list_offer_group, null);
            }
            else {
                nameCompare = offers[position].getCustomerName();
                convertView = inflater.inflate(R.layout.list_offer, null);
            }
    

    This should fix your behavior since now ListView knows you have 2 view types (getViewTypeCount) and which rows in your list are of which type (getItemViewType). It will no longer pass a convertView of type group into a getView call for a row of type non-group and vice versa.

    0 讨论(0)
提交回复
热议问题