25

有没有一种方法可以确保 android listview 中的给定项目完全可见?

我希望能够以编程方式滚动到特定项目,例如当我按下按钮时。

4

5 回答 5

20

ListView.setSelection()将滚动列表,以便所需的项目在视口内。

于 2010-01-01T17:31:53.783 回答
11

试试看:

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;
    }
}
于 2012-02-29T11:30:26.910 回答
5

我相信您正在寻找的是ListView.setSelectionFromTop()(尽管我参加聚会有点晚了)。

于 2012-05-25T08:38:10.847 回答
3

最近我遇到了同样的问题,将我的解决方案粘贴在这里以防有人需要它(我试图使整个最后一个可见项目可见):

    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);
        }
    }
于 2013-05-16T03:34:11.033 回答
2

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);
}
于 2012-06-14T09:50:24.590 回答