android 中擷取當前焦點所在螢幕中的位置 view.getLocationOnScreen(location)

來源:互聯網
上載者:User

標籤:android   style   blog   http   io   ar   os   sp   java   

  View view = getCurrentFocus();//獲得當前焦點所在的view.

Java代碼
     
  1. final int[] location = new int[2];   
  2. view.getLocationOnScreen(location);  
[java] view plaincopy
  1. final int[] location = new int[2];  
  2. view.getLocationOnScreen(location);  


這樣就可以得到該視圖在全域座標系中的x,y值,(注意這個值是要從螢幕頂端算起,也就是索包括了通知欄的高度)//擷取在當前螢幕內的絕對座標

Java代碼  
  1. location[0] x座標   
  2. location[1] y座標  
[java] view plaincopy
  1. location[0] x座標  
  2. location[1] y座標  


應用 ,我們可以用來記錄上一次listview滾動到了那裡

首先我們需要一個記錄當前滾動位置的全域變數:

Java代碼  
  1. private float OldListY = -1;  
[java] view plaincopy
  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 plaincopy
  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); // 恢複剛才的位置  

android 中擷取當前焦點所在螢幕中的位置 view.getLocationOnScreen(location)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.