【发布时间】:2017-07-27 12:58:52
【问题描述】:
我想用onInterceptTouchEvent (MotionEvent ev) 拦截父视图上的触摸事件。
从那里我想知道为了做其他事情而点击了哪个视图,有没有办法知道从收到的运动事件中点击了哪个视图?
【问题讨论】:
我想用onInterceptTouchEvent (MotionEvent ev) 拦截父视图上的触摸事件。
从那里我想知道为了做其他事情而点击了哪个视图,有没有办法知道从收到的运动事件中点击了哪个视图?
【问题讨论】:
对于任何想知道我做了什么的人来说……我不知道。我做了一个解决方法来知道我的特定视图组件是否被点击,所以我只能以这个结束:
if(isPointInsideView(ev.getRawX(), ev.getRawY(), myViewComponent)){
doSomething()
}
以及方法:
/**
* Determines if given points are inside view
* @param x - x coordinate of point
* @param y - y coordinate of point
* @param view - view object to compare
* @return true if the points are within view bounds, false otherwise
*/
public static boolean isPointInsideView(float x, float y, View view){
int location[] = new int[2];
view.getLocationOnScreen(location);
int viewX = location[0];
int viewY = location[1];
//point is inside view bounds
if(( x > viewX && x < (viewX + view.getWidth())) &&
( y > viewY && y < (viewY + view.getHeight()))){
return true;
} else {
return false;
}
}
但这仅适用于布局中可以作为参数传递的已知视图,我仍然无法仅通过知道坐标来获得单击的视图。不过,您可以搜索布局中的所有视图。
【讨论】:
获取被触摸视图的一个简单方法是为各个视图设置一个 OnTouchListener 并将该视图存储在 Activity 的类变量中。 返回 false 将使输入事件可用于 Activity 的 onTouchEvent() 方法,您可以在其中轻松处理所有触摸事件(也是父视图的触摸事件)。
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
touchedView = myView;
return false;
}
});
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
if(touchedView!=null) {
doStuffWithMyView(touchedView);
....
....
【讨论】:
只是为了让htafoya的方法更简单:
/**
* Determines if given points are inside view
* @param x - x coordinate of point
* @param y - y coordinate of point
* @param view - view object to compare
* @return true if the points are within view bounds, false otherwise
*/
private boolean isPointInsideView(float x, float y, View view) {
int location[] = new int[2];
view.getLocationOnScreen(location);
int viewX = location[0];
int viewY = location[1];
// point is inside view bounds
return ((x > viewX && x < (viewX + view.getWidth())) &&
(y > viewY && y < (viewY + view.getHeight())));
}
【讨论】: