Search code examples
androidlistviewbaseadapter

How to scroll to a particular position in a Listview inside Adapter class?


I want to scroll to a particular position in listview, but I have to do it inside the adapter class. I use getItem() method to find out which item I have to scroll to, which is as follows.

public class PropertyListAdapter extends BaseAdapter {

......

@Override
    public Object getItem( int position ) {
        if ( mPositionType[ position ] == DisplayType.Properties ) {

            return getPropertyForPosition( position - mSectionPositionAdjustment[ DisplayType.Properties.ordinal() ] );
        }

        return mPositionType[ position ];
    }

    @Override
    public long getItemId( int position ) {
        return position;
    }

    @Override
    public View getView( int position, View convertView, ViewGroup parent ) {
        return getDisplayView( position, convertView, parent );
    }

......

Now how do I scroll to that position inside this class itself?


Solution

  • If you just want the list to scroll to a specific position:

    myListView.smoothScrollToPosition(i);
    

    if you want to get the position of a specific item in listView:

    myListView.getItemAtPosition(i);
    

    also this listView.getVerticalScrollbarPosition(i);

    }

    if you want to set in the adapter then try to get ListView reference in adapter class below is the code for finding the ListView inside adapter class. have a look

      // See this method of your adapter
     // The parent is the view you are looking for
        public override View GetGroupView(int groupPosition, bool isExpanded, 
         View convertView, ViewGroup parent)
        {
            ListView view = (ListView)parent;
        }