JayceLi  

有时候,listview的哪个item被点击了或触摸了没法很直接的得到。

下面就利用MotionEvent的坐标来计算item位置。

其中有几个值得注意的方法。

getChildAt(),
getGlobalVisibleRect(),
getFirstVisiblePosition(),
 
 1 public void onTapDown(MotionEvent ev, ListView listview)
 2     {
 3         float eY = ev.getY();
 4         Rect r = new Rect();
 5         /*获取第一个可见item相对于listview的可见区域,
 6          * 注意getChildAt(0)得到的是listview这个ViewGroup中的第一个子view,
 7          * 如果listview的adapter中getView进行了优化,
 8          * 则listview的子view个数是屏幕可最多显示的item个数,
 9          * 此时得到的子view并不一定对应adapter数据的第一项。
10          * */
11         listview.getChildAt(0).getGlobalVisibleRect(r);
12         /*这里得到的position是和list数据列表真实对应的*/
13         int first = listview.getFirstVisiblePosition();
14         int index_in_adapter = first;
15         int count = 0;
16         int index_of_childview = 0;
17         
18         /*第一个可见项是listview header*/
19         if(0 == first)
20         {
21             if(eY > r.height())
22             {
23                 /*触摸不在listview header上,根据触摸的Y坐标和listitem的高度计算索引*/
24                 count = (int) ((eY - r.height())/listview.getChildAt(1).getHeight());
25                 index_of_childview = count + 1;
26                 index_in_adapter += count;
27             }
28             else
29             {
30                 /*触摸在listview header上*/
31                 return;
32             }
33         }
34         /*第一个可见项不是listview header*/
35         else
36         {
37             if(eY > r.height())
38             {
39                 /*用触摸点坐标和item高度相除来计算索引*/
40                 count = (int) ((eY - r.height())/listview.getChildAt(1).getHeight());
41                 index_of_childview = count + 1;
42                 index_in_adapter += count;
43             }
44             else
45             {
46                 index_of_childview = 0;
47                 index_in_adapter -= 1;
48             }
49         }
50         
51         /*这即是触摸的那个list item view.*/
52         ViewGroup child_view = (ViewGroup)listview.getChildAt(index_of_childview);
53         /*index_in_adapter即是触摸的子item view在adapter中对应的数据项*/
54         /*index_of_childview即是触摸的item view在listview中的索引*/
55     }
posted on 2012-10-30 16:08  JayceLi  阅读(2099)  评论(0编辑  收藏  举报