Search code examples
androidlistviewlistview-adapter

scrolling programmatically to item in ListView when using CustomListViewAdapter


I am trying to scroll programmatically to a certain position within a list view while using a CustomListViewAdapter.

I use a customlistviewadapter because whenever an item within the listview is clicked, it "opens up" to display some text. It is at that point that I want to scroll programmatically to the top of the text just displayed.

At present, it all works fine, EXCEPT that I don't know how to call the function:

listview.setSelection(currentPosition);

I cannot seem to get to it within the CustomListViewAdapter which is where I listen for the click event on the listview item.

I have tried calling:

parent.setSelected(true);

Just after the item is clicked and the function

notifyDataSetChanged();

is called, but it does nothing.

How can I call

listview.setSelection(currentPosition);

or even better:

listview.smoothScrollToPositionFromTop(position,offset,duration);

Within the CustomListViewAdapter class?

Below is the code of CustomListViewAdapter.

public class CustomListViewAdapter extends ArrayAdapter<RowItem> {

Context context;
ArrayList<RowItem> _rowItems;
RowItem item;
View row;
TextView ReferenceGospel;

  public CustomListViewAdapter(Context context, int resourceId,
                             ArrayList<RowItem> rowItems) {


    super(context, resourceId, rowItems);
    this.context = context;
    _rowItems = rowItems;
}

@Override
public View getView(final int position, View convertView, final ViewGroup parent) {
row = convertView;
item = _rowItems.get(position);

 if (row == null) {
        LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row = mInflater.inflate(R.layout.book_list, parent, false);
        row.setTag(thisPosition);

    }

ReferenceGospel = (TextView) row.findViewById(R.id.gospelRef);

// ... some other code here

ReferenceGospel.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            item = _rowItems.get(position);
            CustomListViewAdapter.this.notifyDataSetChanged();
  }
     });
    return row;
}

I have looked at several posts but none help. Thank you.


Solution

  • Pass the listview in constructor of adapter:

    ListView listView;
    
      public CustomListViewAdapter(Context context, ListView listView,
                             ArrayList<RowItem> rowItems) {
    
    
     super(context, resourceId, rowItems);
     this.context = context;
     this.listView = listView;
     _rowItems = rowItems;
    
    }
    

    then you can call listview.smoothScrollToPositionFromTop(position,offset,duration); from getView method.

    Hope it helps.