user149408
user149408

Reputation: 5901

Scroll a particular ListView item into view

In my application, I have a ListView. The data for each item in the list is an instance of the SomeItem class. The list has a custom ArrayAdapter which has a custom view to display various fields of each items and overrides the getView() method. Skeleton code for the initialization of the list view:

ListView listView = (ListView) foo.getViewById(R.id.listView);

ArrayAdapter<SomeItem> adapter = new ArrayAdapter<SomeItem>(activity, R.layout.listItemView, R.id.textView) {
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Code to build the view with multiple child views
    }
}

Now assume I have a SomeItem instance. Its associated view may or may not be in the portion of the ListView which is shown on screen. If it is not, how can I get the ListView to scroll this particular item into view?

The only somewhat related method I’ve found is ListView#requestChildRectangleOnScreen(), which requires me to provide a child view which I don’t have. I have the item for the adapter. So I’m still not sure how to piece this together. Any pointers?

Upvotes: 0

Views: 415

Answers (1)

Dmitry Akishin
Dmitry Akishin

Reputation: 119

You can try the following:

  1. Calculate the position of the SomeItem item you want to make visible. You can do this by iterating over the list of SomeItems that you pass to the adapter.

  2. Use listView.getFirstVisiblePosition(), listView.getLastVisiblePosition() and the calculated position to check if the item is visible on the list.

  3. If the item is not visible, make listView scroll to it by calling listView.smoothScrollToPosition(calculatedPosition).

Upvotes: 1

Related Questions