Android 如何将ListView中的目标项目显示在屏幕顶部

Android 如何将ListView中的目标项目显示在屏幕顶部,android,listview,scrollview,Android,Listview,Scrollview,我正在编写一个android应用程序,其中包含一个列表视图和一些项目(通过数据库获取,可以是100+) 我希望滚动listview以显示特定项目(比如listview中的位置x) 我曾经 视图已滚动。但一旦项目出现,它就停止了。(该项目现在显示在屏幕底部) 我认为更好的设计是在屏幕顶部或至少在屏幕中间显示项目。 我该怎么做 我现在正在寻找一种方法,找到在屏幕上真正可见的listview索引。 我尝试过getFirstVisiblePosition(),但它似乎总是返回0。您会发现它比smooth

我正在编写一个android应用程序,其中包含一个列表视图和一些项目(通过数据库获取,可以是100+) 我希望滚动listview以显示特定项目(比如listview中的位置x) 我曾经

视图已滚动。但一旦项目出现,它就停止了。(该项目现在显示在屏幕底部) 我认为更好的设计是在屏幕顶部或至少在屏幕中间显示项目。 我该怎么做

我现在正在寻找一种方法,找到在屏幕上真正可见的listview索引。 我尝试过getFirstVisiblePosition(),但它似乎总是返回0。

您会发现它比
smoothScrollToPosition()更好。如果在后台加载支持ListView的数据,则需要延迟发出
setSelection()
,直到数据加载完毕

getFirstVisiblePosition()
对我来说很好,但也只有在加载所有数据后才有用。下面是我用于显示从远程站点获取的数据的ListView的一些代码:

    // the list has been updated, fix the selection. loadFinished will be true if there are no phantom placeholders left.
protected void listLoaded(boolean loadFinished) {
    // if the user has scrolled or we previously completed resetting the position, do nothing
    if(wasScrolled)
        return;
            // if we were restored from saved data, reload that data now.
    if(listState != null) {
        postListView.onRestoreInstanceState(listState);
        listState = null;
    } else if(initialPos >= 0) // if we had a specific initial position, set it now
        setSelection(initialPos);
    else if(postId >= 0)  // or if there is a specific post ID we want displayed
        setSelection(postAdapter.getPostPosition(postId));
    else // otherwise scroll to the first unread post
        setSelection(postAdapter.getFirstUnread());
    if(loadFinished) // if all data has been loaded, set a flag to prevent this being repeated
        wasScrolled = true;
}
    // the list has been updated, fix the selection. loadFinished will be true if there are no phantom placeholders left.
protected void listLoaded(boolean loadFinished) {
    // if the user has scrolled or we previously completed resetting the position, do nothing
    if(wasScrolled)
        return;
            // if we were restored from saved data, reload that data now.
    if(listState != null) {
        postListView.onRestoreInstanceState(listState);
        listState = null;
    } else if(initialPos >= 0) // if we had a specific initial position, set it now
        setSelection(initialPos);
    else if(postId >= 0)  // or if there is a specific post ID we want displayed
        setSelection(postAdapter.getPostPosition(postId));
    else // otherwise scroll to the first unread post
        setSelection(postAdapter.getFirstUnread());
    if(loadFinished) // if all data has been loaded, set a flag to prevent this being repeated
        wasScrolled = true;
}