我想要相对于整个屏幕的触摸信息,但是我只是相对于按钮获得触摸信息.
ButtonTouchListener = new OnTouchListener(){
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
switch(v.getId()){
case R.id.somebutton
//do things
//....etc
}
int action = event.getAction();
switch(action){
case MotionEvent.ACTION_UP:
act += event.toString();
System.out.println("release: " + act);
}};
我从事件中获得的x和y与按钮有关(0,0是按钮的角,而不是屏幕的角).仅当按下按钮时,如何才能获得相对于整个屏幕的x和y位置?
解决方法:
要获得相对于视图的触摸位置,请将触摸事件的(x,y)添加到按钮的(x,y);要获取按钮相对于其父控件(您的视图)的位置,请使用getLeft()和getTop()方法.
View的documentation在“位置”下具有以下内容:
It is possible to retrieve the location of a view by invoking the
methods getLeft() and getTop(). The former returns the left, or X,
coordinate of the rectangle representing the view. The latter returns
the top, or Y, coordinate of the rectangle representing the view.
These methods both return the location of the view relative to its
parent. For instance, when getLeft() returns 20, that means the view
is located 20 pixels to the right of the left edge of its direct
parent.
您的onTouch方法的示例代码:
float screenX = v.getLeft() + event.getX(); // X in Screen Coordinates
float screenY = v.getTop() + event.getY(); // Y in Screen Coordinates