Search code examples
androidlistviewandroid-cursoradapter

get a position in bindView using CursorAdapter


i am create a listview which has two TextView and one custom view as a selection indicator , to load data i am using CursorAdapter and overriding bindView and newView. but the issue is in preserving the selection index.

when i am tapping a list item , i am saving the position of it into view as follows

View v1=(View)view.findViewById(R.id.viewColor);
v1.setTag(position)

but inside a bindView i not getting a position where i can perform a match by fetching position from view's tag as follows

 Integer position = (Integer) v1.getTag();

but i am not getting a position to compare just the way we get in getView. i tried cur.getPosition() is the position of a record in cursor which wont match with the v1.getTag().

i tried overriding getView as follows , but not getting accurate position

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

    this.position = position;
    return super.getView(position, convertView, parent);


}

so how i can i get the position in bindView ? do i need to use getView or what ? i explored many threads but i didn't get any definite answer when it comes to bindView.

EDIT

        @Override
        public void onItemClick(AdapterView<?> adapter, View view, int position,
                long arg3) {


                    view.setTag(position); 
                   // i save the position on list item click so that when adapter loads the 
                   // the list i can match the position with the current one

          }

enter image description here


Solution

  • For This first you need to override getView() and set the position here and access it in bindview() later.

    @Override
    public View getView(int position, View convertview, ViewGroup arg2) {
        if (convbertview == null) {
            LayoutInflater inflater = LayoutInflater.from(context);
            convertview = inflater.inflate(R.layout.your layout,
                    null);
        }
        convertview.setTag(position);
        return super.getView(position, convbertview, arg2);
    }
    

    and in bindView() get your position like

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        int position=(Integer) view.getTag();//here is the position
    
    }