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); // 恢復剛才的位置  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM