ensure visible on android listview?
Is there a way that I can makle sure a given item in an android listview is entirely visible?
I'd like to be able to programmatically scroll to a specific item, like when I pres开发者_StackOverflow中文版s a button for example.
ListView.setSelection()
will scroll the list so that the desired item is within the viewport.
Try it:
public static void ensureVisible(ListView listView, int pos)
{
if (listView == null)
{
return;
}
if(pos < 0 || pos >= listView.getCount())
{
return;
}
int first = listView.getFirstVisiblePosition();
int last = listView.getLastVisiblePosition();
if (pos < first)
{
listView.setSelection(pos);
return;
}
if (pos >= last)
{
listView.setSelection(1 + pos - (last - first));
return;
}
}
I believe what you are looking for is ListView.setSelectionFromTop() (although I'm a bit late to the party).
Recently I met the same problem, paste my solution here in case someone need it (I was trying to make the entire last visible item visible):
if (mListView != null) {
int firstVisible = mListView.getFirstVisiblePosition()
- mListView.getHeaderViewsCount();
int lastVisible = mListView.getLastVisiblePosition()
- mListView.getHeaderViewsCount();
View child = mListView.getChildAt(lastVisible
- firstVisible);
int offset = child.getTop() + child.getMeasuredHeight()
- mListView.getMeasuredHeight();
if (offset > 0) {
mListView.smoothScrollBy(offset, 200);
}
}
I have a shorter and, in my opinion, better solution to do this : ListView requestChildRectangleOnScreen method is designed for it.
The answer above ensures that the item will be displayed, but sometimes it will be displayed partly (ie. when it is at the bottom of the screen). The code below ensures that the whole item will be displayed and that the view will scroll only the necessary zone :
private void ensureVisible(ListView parent, View view) {
Rect rect = new Rect(view.getLeft(), view.getTop(), view.getRight(), view.getBottom());
parent.requestChildRectangleOnScreen(view, rect, false);
}
精彩评论