Stop scrolling in a listview

2019-03-26 17:55发布

I have in my activity a listview and an imagebutton. When I click the imagebutton I want to go to a specific position in the list (I do this by calling: setSelection(int position) on the list. The problem occurs when the user flings the listview and then clicks the imagebutton. The list goes to the specified position but continues scrolling.

eg. when I go into fling mode, click the button, then I go to the fourth position, but the listview keeps scrolling, so I end up with a selection of 25

6条回答
走好不送
2楼-- · 2019-03-26 18:07

I have write simple method to stop scoll ListView using reflection.

private void stopScroll(AbsListView view)
{
    try
    {
        Field field = android.widget.AbsListView.class.getDeclaredField("mFlingRunnable");
        field.setAccessible(true);
        Object flingRunnable = field.get(view);
        if (flingRunnable != null)
        {
            Method method = Class.forName("android.widget.AbsListView$FlingRunnable").getDeclaredMethod("endFling");
            method.setAccessible(true);
            method.invoke(flingRunnable);
        }
    }
    catch (Exception e) {}
}

Just call stopScroll(myListView); when you need to stop scroll.

查看更多
smile是对你的礼貌
3楼-- · 2019-03-26 18:07

I would try calling ListView.smoothScrollToPosition(int position) to scroll back to the right position. As all the gui stuff is done in one thread I think there's little chance to really stop the scrolling on button press, so the easiest would be scrolling back (which might even be a nice gui effect too).

查看更多
戒情不戒烟
4楼-- · 2019-03-26 18:13
// Stop scrolling
smoothScrollBy(0, 0);

Internally this will call the method that @Nik is trying to reflect.

查看更多
做个烂人
5楼-- · 2019-03-26 18:15

did you try listView.clearAnimation() ? it might work

查看更多
欢心
6楼-- · 2019-03-26 18:17

Use

listView.smoothScrollBy(0, 0); // to stop the scrolling.
// followed by
listView.setSelection(position) // to move to the specific position.
查看更多
啃猪蹄的小仙女
7楼-- · 2019-03-26 18:28

You have a method for manual scrolling you can call listview.scrollTo(int, int); But I do not have idea how can you calculate how much to scroll, I mean how to calculate the arguments of the method. Also this doesn't stop scrolling it just positions you at a specific place and then stop scrolling, so you might have a little flicker... If doesn't solve you problem at list will give some hints.

more about the method

查看更多
登录 后发表回答