如何在Android ListView中从顶部的特定偏移量获取项目的索引

时间:2013-03-13 16:55:38

标签: android android-widget android-listview android-ui

是否有一种简单的方法可以获取列表项的索引,该列表项位于顶部的特定偏移量中? 例如,获取从顶部出现150像素的项目的索引。

2 个答案:

答案 0 :(得分: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) {

    }
}

答案 1 :(得分:0)

您可以遍历子项,并根据您拥有的点检查每个点击矩形。