質問

I need to place a divider after nth element in the list view that is generated from a mysqli cursor. I created custom adapter that tries to do that, like this:

MyAdapter extends CursorAdapter {

     ...
     blablabla
     yadayadayada
     ...

     @Override
     public View newView(Context context, Cursor cursor, ViewGroup parent) {

         final View view;
         int pos = cursor.getPosition();
         int beforeLast = GameData.totalPlayers-1;
         if (pos == beforeLast) {
             view = mInflater.inflate(R.layout.player_details_divider, parent, false);
         } else {
             view = mInflater.inflate(R.layout.player_details, parent, false);
         }
         return view;
     }
}

So as you can see its supposed to inflate different view for an element on a position totalPlayers-1. It works great when number is small enough: 1 through 6. But when its bigger it just stops working.

I tried debugging the thing and I noticed that it renders 6 items - this is how much list elements fits on the screen - and goes through the loop 6 times incrementing pos to 5. Then it stops. When I start scrolling the list, it runs the loop again, incrementing pos to 6 and then it stops. No matter how many elements there are it just never increments pos to 7 (although all data are present in the list, so cursor must be iterated to the end).

Any ideas why it behaves like this? What is it I am not understanding/doing wrong?

役に立ちましたか?

解決

Issue seems to be due to the ListView recycle. ListView will try to reuse the same view for the items. So in your case , newView is called for first 6 visible items and when you scroll ListView resizes the same 6 items views for the next 6 item in the list.

You need to update the ListView, that you have 2 different item view, so that it know your last item views is different from others

You need to override the getViewTypeCount and return that you have 2 different view

@Override
public int getViewTypeCount() {
    return 2; // return the view type
}

Also, override getItemViewType and inform ListView that the last position view is the one different.

Override
public int getItemViewType(int position){
    int beforeLast = GameData.totalPlayers-1;
    // return a unique number
    if(beforeLast == position) {
        return 1; // some unique id
    }else {
        return 0;
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top