2013-03-13 84 views
1

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

+0

也许你可以更多地解释你打算做什么 - 这听起来像是它可能是一种不会很好地工作的方法。 – NPike 2013-03-13 16:58:54

+0

我想知道位于屏幕中间的项目的索引是什么。 – 2013-03-13 17:00:59

回答

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) { 

    } 
} 
0

您可以通过孩子迭代并检查每个那些碰到你点的矩形。

相关问题