问题
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?
回答1:
You can try the following:
Calculate the position of the
SomeItem
item you want to make visible. You can do this by iterating over the list ofSomeItem
s that you pass to the adapter.Use
listView.getFirstVisiblePosition()
,listView.getLastVisiblePosition()
and the calculated position to check if the item is visible on the list.If the item is not visible, make
listView
scroll to it by callinglistView.smoothScrollToPosition(calculatedPosition)
.
来源:https://stackoverflow.com/questions/46595361/scroll-a-particular-listview-item-into-view