View view = Getcurrentfocus ();//Gets the view where the current focus is.
Java code
- Final int[] location = new int[2];
- View.getlocationonscreen (location);
[Java]View Plaincopy
- Final int[] location = new int[2];
- View.getlocationonscreen (location);
This will give you the X, Y value of the view in the global coordinate system (note that this value is calculated from the top of the screen, that is, the height of the notification bar is included)//Gets the absolute coordinates in the current screen
Java code
- location[0] x coordinate
- location[1] y-coordinate
[Java]View Plaincopy
- location[0] x coordinate
- location[1] y-coordinate
Application that we can use to record the last time the ListView was scrolled there
First we need a global variable that records the current scrolling position:
Java code
- Private Float oldlisty =-1;
[Java]View Plaincopy
- Private Float oldlisty =-1;
Then get oldlisty in the Onitemclick () or Onitemlongclick () event of the ListView:
Java code
- Lstview.setonitemclicklistener (new Onitemclicklistener ()
- {
- public void Onitemclick (adapterview<?> arg0, View arg1, int arg2, long arg3)
- {
- int pos[] = {-1,-1}; //Save an array of current coordinates
- Arg1.getlocationonscreen (Pos); //Gets the position of the selected Item in the screen, with the upper-left corner as the origin (0, 0) .
- Oldlisty = (float) pos[1]; //We'll just take the Y-coordinate.
- }
- });
[Java]View Plaincopy
- Lstview.setonitemclicklistener (new Onitemclicklistener ()
- {
- public void Onitemclick (adapterview<?> arg0, View arg1, int arg2, long arg3)
- {
- int pos[] = {-1,-1}; //Save an array of current coordinates
- Arg1.getlocationonscreen (Pos); //Gets the position of the selected Item in the screen, with the upper-left corner as the origin (0, 0) .
- Oldlisty = (float) pos[1]; //We'll just take the Y-coordinate.
- }
- });
The last thing to do is to restore the previous position after Setadapter ():
Java code
- ...
- Lstview.setadapter (adapter); //rebind adapter
- Lstview.setselectionfromtop (index, (int) oldlisty); //Restore the location just now
The location in the screen where the current focus is captured in Android View.getlocationonscreen