Search code examples
androidlistviewposition

Wrong position number in a ListView


I got this problem several times and even though I can't solve it

here's code from Adapter

    public View getView(final int position, View convertView, ViewGroup parent) {


        if(convertView == null){
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.place_item_layout, parent, false);
            //HERE's my check
            (convertView.findViewById(R.id.divdePlaces)).setVisibility(View.GONE);
            if (place.isTOP()==false && position!=0) if (places.get(position-1).isTOP()==true) {
                //turn back on
                (convertView.findViewById(R.id.divdePlaces)).setVisibility(View.VISIBLE);   
            }

.. etc..

}
return convertView;
}

So, this just turn on the divider line if conditions are met. I thought here the position should be the real number but it repeats again when ListView goes 1 screen up, even though the conditions for it are not met for sure.

How do I fix that?

enter image description here

enter image description here


Solution

  • As you scroll one page up, your views start to get recycled. Hence, convertView is already inflated and non-null. Toggle the visibility of the divider outside of the if (convertView==null) block.

    Something like this:

    public View getView(final int position, View convertView, ViewGroup parent)
    {
    
    
        if(convertView == null)
        {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService Context.LAYOUT_INFLATER_SERVICE);
    
            convertView = inflater.inflate(R.layout.place_item_layout, parent, false);
        }
    
        int visibility = (place.isTOP()==false && position!=0) ? View.GONE : View.VISIBLE;
        convertView.findViewById(R.id.divdePlaces).setVisibility(visibility);
    
        return convertView;
    
    }