android 中获取当前焦点所在屏幕中的位置 view.getLocationOnScreen(location)

  View view = getCurrentFocus();//获得当前焦点所在的view.

Java代码 复制代码 收藏代码
     
  1. final int[] location = new int[2];   
  2. view.getLocationOnScreen(location);  
[java] view plain copy
  1. final int[] location = new int[2];  
  2. view.getLocationOnScreen(location);  


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

Java代码 复制代码  收藏代码
  1. location[0] x坐标   
  2. location[1] y坐标  
[java] view plain copy
  1. location[0] x坐标  
  2. location[1] y坐标  


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

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

Java代码 复制代码  收藏代码
  1. private float OldListY = -1;  
[java] view plain copy
  1. private float OldListY = -1;  


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


Java代码 复制代码  收藏代码
  1. lstView.setOnItemClickListener(new OnItemClickListener()   
  2. {   
  3.     public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)   
  4.     {   
  5.         int Pos[] = { -1, -1 };  //保存当前坐标的数组  
  6.         arg1.getLocationOnScreen(Pos);  //获取选中的 Item 在屏幕中的位置,以左上角为原点 (0, 0)  
  7.         OldListY = (float) Pos[1];  //我们只取 Y 坐标就行了  
  8.     }   
  9. });  
[java] view plain copy
  1. lstView.setOnItemClickListener(new OnItemClickListener()  
  2. {  
  3.     public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)  
  4.     {  
  5.         int Pos[] = { -1, -1 };  //保存当前坐标的数组  
  6.         arg1.getLocationOnScreen(Pos);  //获取选中的 Item 在屏幕中的位置,以左上角为原点 (0, 0)  
  7.         OldListY = (float) Pos[1];  //我们只取 Y 坐标就行了  
  8.     }  
  9. });  


最后要做的就是在 setAdapter() 后恢复先前的位置:

Java代码 复制代码  收藏代码
  1. ...   
  2. lstView.setAdapter(adapter); // 重新绑定Adapter  
  3. lstView.setSelectionFromTop(index, (int) OldListY); // 恢复刚才的位置  

转载于:https://www.cnblogs.com/zhongle/p/4151345.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值