代码之家  ›  专栏  ›  技术社区  ›  htafoya

如何从android中的事件坐标获取视图?

  •  25
  • htafoya  · 技术社区  · 14 年前

    我想截取父视图上的触摸事件 onInterceptTouchEvent (MotionEvent ev)

    从那里我想知道哪个视图被点击是为了做其他的事情,有没有办法知道哪个视图被点击从那个运动事件接收?

    3 回复  |  直到 8 年前
        1
  •  80
  •   htafoya    11 年前

    如果有人想知道我做了什么。。。我不能。我做了一个变通方法来确定是否单击了我的特定视图组件,因此我只能以以下内容结束:

       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;
        }
    }
    

    但是,这只适用于布局中可以作为参数传递的已知视图,我仍然无法仅通过知道坐标来获取单击的视图。但是,您可以搜索布局中的所有视图。

        2
  •  4
  •   Christopher Masser    13 年前

    获取触摸视图的一个简单方法是将OnTouchListener设置为各个视图,并将该视图存储在活动的类变量中。

    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);
                ....
                ....
    
        3
  •  3
  •   schmidt9    9 年前

    只是为了让方法 更简单:

    /**
    * 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())));
    }