确保在android listview上可见?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1988916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ensure visible on android listview?
提问by CodeFusionMobile
Is there a way that I can makle sure a given item in an android listview is entirely visible?
有没有办法可以确保 android 列表视图中的给定项目完全可见?
I'd like to be able to programmatically scroll to a specific item, like when I press a button for example.
我希望能够以编程方式滚动到特定项目,例如当我按下按钮时。
回答by Christopher Orr
ListView.setSelection()
will scroll the list so that the desired item is within the viewport.
ListView.setSelection()
将滚动列表,以便所需的项目在视口内。
回答by jauseg
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;
}
}
回答by Jonas Rabbe
I believe what you are looking for is ListView.setSelectionFromTop()(although I'm a bit late to the party).
我相信你正在寻找的是ListView.setSelectionFromTop()(虽然我参加聚会有点晚了)。
回答by liuyong
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);
}
}
回答by Yves Delerm
I have a shorter and, in my opinion, better solution to do this : ListView requestChildRectangleOnScreen method is designed for it.
我有一个更短的,在我看来,更好的解决方案来做到这一点:ListView requestChildRectangleOnScreen 方法是为它设计的。
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);
}