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

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:


spa

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() 后恢复先前的位置: .net

Java代码 复制代码  收藏代码
  1. ...   
  2. lstView.setAdapter(adapter); // 从新绑定Adapter  
  3. lstView.setSelectionFromTop(index, (int) OldListY); // 恢复刚才的位置  
相关文章
相关标签/搜索