2011.07.20——— android 获得当前view在屏幕的座标

2011.07.20——— android 获得当前view在屏幕的坐标
2011.07.20——— android 获得当前view在屏幕的坐标

参考:http://archive.cnblogs.com/a/2111143/
http://www.littledai.com/20110227/162258/536



final int[] location = new int[2];
view.getLocationOnScreen(location);



这样就可以得到该视图在全局坐标系中的x,y值,(注意这个值是要从屏幕顶端算起,也就是索包括了通知栏的高度)//获取在当前屏幕内的绝对坐标

location[0] x坐标
location[1] y坐标


应用 ,我们可以用来记录上一次listview滚动到了那里

首先我们需要一个记录当前滚动位置的全局变量:


private float OldListY = -1;

然后在 listView 的 onItemClick() 或 onItemLongClick() 事件中获取 OldListY:


lstView.setOnItemClickListener(new OnItemClickListener()
{
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
    {
        int Pos[] = { -1, -1 };  //保存当前坐标的数组
        arg1.getLocationOnScreen(Pos);  //获取选中的 Item 在屏幕中的位置,以左上角为原点 (0, 0)
        OldListY = (float) Pos[1];  //我们只取 Y 坐标就行了
    }
});

最后要做的就是在 setAdapter() 后恢复先前的位置:
...
lstView.setAdapter(adapter); // 重新绑定Adapter
lstView.setSelectionFromTop(index, (int) OldListY); // 恢复刚才的位置