列表视图对齐到项目 [英] List view snap to item

查看:25
本文介绍了列表视图对齐到项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ListView 创建一个图片列表,并且这些照片的大小可以在屏幕上容纳 2 到 3 张照片.

I'm creating a list of pictures using a ListView and the photos are of a size that would fit 2 to 3 photos on the screen.

我遇到的问题是,当用户停止滚动时,我希望可见列表的第一项会对齐到屏幕顶部,例如,如果滚动结束并且第一项的一小部分图片显示,我们向下滚动列表,以便图片始终完全显示,如果大部分图片都显示,我们向上滚动列表,以便下一张图片完全可见.

The problem that I'm having is that I would like to when the user stops scrolling that the first item of the visible list would snap to the top of screen, for example, if the scroll ends and small part of the first picture displayed, we scroll the list down so the picture is always fully displayed, if mostly of the picture is displayed, we scroll the list up so the next picture is fully visible.

有没有办法在 android 中使用列表视图来实现这一点?

Is there a way to achieve this in android with the listview?

推荐答案

我找到了一种方法来做到这一点,只需通过实现 ListView.OnScrollListener 来监听滚动并在滚动结束时更改位置

I've found a way to do this just listening to scroll and change the position when the scroll ended by implementing ListView.OnScrollListener

@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
    switch (scrollState) {
    case OnScrollListener.SCROLL_STATE_IDLE:
        if (scrolling){
            // get first visible item
            View itemView = view.getChildAt(0);
            int top = Math.abs(itemView.getTop()); // top is a negative value
            int bottom = Math.abs(itemView.getBottom());
            if (top >= bottom){
                ((ListView)view).setSelectionFromTop(view.getFirstVisiblePosition()+1, 0);
            } else {
                ((ListView)view).setSelectionFromTop(view.getFirstVisiblePosition(), 0);
            }
        }
        scrolling = false;
        break;
    case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
    case OnScrollListener.SCROLL_STATE_FLING:
        Log.i("TEST", "SCROLLING");
        scrolling = true;
        break;
    }
}

变化不是那么顺利,但确实有效.

The change is not so smooth but it works.

这篇关于列表视图对齐到项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆