android獲得當前view在螢幕中座標的方法_Android

來源:互聯網
上載者:User

本文執行個體講述了android獲得當前view在螢幕中座標的方法。分享給大家供大家參考。具體如下:

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); // 重新綁定AdapterlstView.setSelectionFromTop(index, (int) OldListY); // 恢複剛才的位置

希望本文所述對大家的Android程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.