標籤:android style blog http io ar os sp java
View view = getCurrentFocus();//獲得當前焦點所在的view.
Java代碼
- final int[] location = new int[2];
- view.getLocationOnScreen(location);
[java] view plaincopy
- final int[] location = new int[2];
- view.getLocationOnScreen(location);
這樣就可以得到該視圖在全域座標系中的x,y值,(注意這個值是要從螢幕頂端算起,也就是索包括了通知欄的高度)//擷取在當前螢幕內的絕對座標
Java代碼
- location[0] x座標
- location[1] y座標
[java] view plaincopy
- location[0] x座標
- location[1] y座標
應用 ,我們可以用來記錄上一次listview滾動到了那裡
首先我們需要一個記錄當前滾動位置的全域變數:
Java代碼
- private float OldListY = -1;
[java] view plaincopy
- private float OldListY = -1;
然後在 listView 的 onItemClick() 或 onItemLongClick() 事件中擷取 OldListY:
Java代碼
- 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 座標就行了
- }
- });
[java] view plaincopy
- 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() 後恢複先前的位置:
Java代碼
- ...
- lstView.setAdapter(adapter); // 重新綁定Adapter
- lstView.setSelectionFromTop(index, (int) OldListY); // 恢複剛才的位置
android 中擷取當前焦點所在螢幕中的位置 view.getLocationOnScreen(location)