SoFunction
Updated on 2025-03-11

How to get the coordinates of the current view in the screen

This article example describes the method of android to obtain the coordinates of the current view in the screen. Share it for your reference. The details are as follows:

final int[] location = new int[2];
(location);

This way you can get the x and y values ​​of the view in the global coordinate system (note that this value must be calculated from the top of the screen, which means that the height of the notification bar is included)

//Get the absolute coordinates in the current screenlocation[0] xcoordinate
location[1] ycoordinate

Apply, we can use it to record the last listview scrolling there

First we need a global variable that records the current scroll position:

Copy the codeThe code is as follows:
private float OldListY = -1;

Then get OldListY in the onItemClick() or onItemLongClick() event of the listView:

(new OnItemClickListener()  
{  
  public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
  {
    int Pos[] = { -1, -1 }; //Save the array of current coordinates    (Pos); //Get the selected Item's position in the screen, with the upper left corner as the origin (0, 0)    OldListY = (float) Pos[1]; //We just need to take the Y coordinates  }
});

The last thing to do is to restore the previous position after setAdapter():

...  
(adapter); // Rebound Adapter(index, (int) OldListY); // Restore the position just now

I hope this article will be helpful to everyone's Android programming design.