1

有没有一种简单的方法来获取距顶部特定偏移量的列表项的索引?例如,获取距顶部 150 像素的项目的索引。

4

2 回答 2

1

由于您的目标是找到位于屏幕中央的列表项,因此您可以尝试以下操作:

(制作一个扩展ListView的自定义类,如MyListView.java)

public class MyListView extends ListView implements OnScrollListener {

public MyListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setOnScrollListener(this);
    }


@Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        // Center the child currently closest to the center of the ListView when
        // the ListView stops scrolling.
        if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) { 

            int listViewCenterX = getWidth() / 2;
            int listViewCenterY = getHeight() / 2;

            Rect rect = new Rect();

            // Iterate the children and find which one is currently the most
            // centered.
            for (int i = 0; i < getChildCount(); ++i) {
                View child = getChildAt(i);
                child.getHitRect(rect);
                if (rect.contains(listViewCenterX, listViewCenterY)) {
                    // this listitem is in the "center" of the listview
                    // do what you want with it.
                    final int position = getPositionForView(child);
                    final int offset = listViewCenterY - (child.getHeight() / 2);
                    break;
                }
            }
        }
    }


    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

    }
}
于 2013-03-13T17:15:48.043 回答
0

您可以遍历孩子并检查每个孩子是否与您所拥有的点相匹配。

于 2013-03-13T17:04:35.180 回答