简体   繁体   English

ListView 滚动到所选项目

[英]ListView scroll to selected item

I have a ListView with an edit text and a button below it.我有一个带有编辑文本的 ListView 和它下面的按钮。 When I click on a listView item the keyboard appears and push up the edit text and the button.当我点击一个 listView 项目时,键盘出现并向上推编辑文本和按钮。 I want the list to scroll to the selected item.我希望列表滚动到所选项目。 Any idea?任何的想法? Thanks谢谢

您可以使用 ListView 的setSelection(int position)方法滚动到一行。

您可以使用 ListView 的smoothScrollToPosition(int position)滚动到列表中的特定位置。

For a direct scroll:对于直接滚动:

getListView().setSelection(11);

For a smooth scroll:对于平滑滚动:

getListView().smoothScrollToPosition(11);

To Scroll to top滚动到顶部

getListView().setSelectionAfterHeaderView();

Note笔记

try to call it in post because sometime listview is not yet created while you calling it's method尝试在 post 中调用它,因为有时在调用它的方法时还没有创建 listview

getListView().postDelayed(new Runnable() {          
    @Override
    public void run() {
        lst.setSelection(15);
    }
},100L);

您应该使用transcript mode

getListView().setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);

Setup a listener on your the list item being clicked, then use View.getTop() or View.getBottom() when clicked to get it's position within the parent.在被单击的列表项上设置一个侦听器,然后在单击时使用View.getTop()View.getBottom()以获取它在父项中的位置。 You can then use ListView.scrollTo(x, y) to scroll to the list item.然后您可以使用ListView.scrollTo(x, y)滚动到列表项。

Yo can look For你可以寻找

listView.setSelectionFromTop(position, distanceFromHeader); listView.setSelectionFromTop(position, distanceFromHeader);

It will position the Item at position , specified pixels below the top of listview它将把 Item 定位在 listview 顶部下方指定像素的位置

You can use您可以使用

smoothScrollToPosition(position)

Just increase the position of item with 1, and you will get the view of item.只需将 item 的位置增加 1,您将获得 item 的视图。

getListView().smoothScrollToPosition(position + 1);

Using duration gives a better user experience.使用持续时间可以提供更好的用户体验。 Use this, with duration added.使用它,并添加持续时间。 Will scroll the item in position smoothly to the top of the listview.将位置中的项目平滑地滚动到列表视图的顶部。

int duration = 500;  //miliseconds
int offset = 0;      //fromListTop

listview.smoothScrollToPositionFromTop(position,offset,duration);
  • descrease duration to make scrolling faster减少持续时间以加快滚动速度

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM