This paper illustrates the Motionevent coordinate acquisition method in Android development. Share to everyone for your reference, specific as follows:
The Android motionevent getx () and GETRAWX () are all getting screen coordinates (horizontal), but there's a difference
GetX (): is the coordinate to get relative to the current control (View)
GETRAWX (): Gets the coordinates of the upper-left corner of the display screen
Demo Sample Code
Java code:
public class Mainactivity extends activity implements Ontouchlistener {
private Button btn;
private int x = 0, y = 0;
private int rawx = 0, Rawy = 0;
@Override
protected void onCreate (Bundle savedinstancestate) {
super.oncreate (savedinstancestate);
Setcontentview (r.layout.main);
BTN = (Button) Findviewbyid (R.ID.BTN);
Btn.setontouchlistener (this);
}
@Override Public
Boolean Ontouch (view view, Motionevent event) {
int eventaction = Event.getaction ();
Switch (eventaction) {case
motionevent.action_down: Break
;
Case Motionevent.action_move:
x = (int) event.getx ();
y = (int) event.gety ();
RAWX = (int) event.getrawx ();
Rawy = (int) event.getrawy ();
LOG.E ("Homer", "x =" + x +); y = "+ y +"; RAWX = "+ Rawx +"; Rawy = "+ Rawy);
break;
Case MOTIONEVENT.ACTION_UP: Break
;
}
return false;
}
}
XML code:
<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"
xmlns:tools= "http:// Schemas.android.com/tools "
android:layout_width=" fill_parent "
android:layout_height=" Fill_parent
" Tools:context= ". Mainactivity ">
<textview
android:id=" @+id/txt "
android:layout_width=" Wrap_content " android:layout_height= "Wrap_content"
android:layout_centerhorizontal= "true"
android:layout_ Centervertical= "true"
android:text= "@string/hello_world"/>
<button android:id=
"@+id/btn"
android:layout_width= "wrap_content"
android:layout_height= "wrap_content"
android:layout_below= "@id/txt"
android:layout_centerinparent= "true"
android:text= "button Me"/>
</relativelayout >
Run Result:
Click the button in the middle of the screen to get the coordinate information:
Results show:
X,y: The coordinate GetX () of the relative button controls obtained separately, GetY ()
Rawx,rawy: The coordinates of the upper-left corner of the display screen are obtained separately getrawx (), Getrawy ()
Summarize:
GetX () is the x-coordinate that represents the widget relative to its upper-left corner. The GETRAWX () is the x-coordinate relative to the upper-left corner of the screen (note: The upper-left corner of the screen is the upper left of the phone screen, regardless of whether the activity is titlebar or full screen); GetY (), Getrawy () The same truth
More readers interested in Android-related content can view this site: Android Development Primer and Advanced tutorial, Android mobile phone information How-to summary, Android resource Operation tips Summary and Android Basic component Usage Summary
I hope this article will help you with the Android program.