check if MotionEvent is In View - Android User Interface

Android examples for User Interface:Touch Event

Description

check if MotionEvent is In View

Demo Code


//package com.java2s;

import android.graphics.Rect;

import android.view.MotionEvent;
import android.view.View;

public class Main {
    public static boolean eventInView(MotionEvent event, View view) {
        if (event == null || view == null) {
            return false;
        }/*from w  ww  . j av  a2  s. c  o  m*/

        int eventX = (int) event.getRawX();
        int eventY = (int) event.getRawY();

        int[] location = new int[2];
        view.getLocationOnScreen(location);

        int width = view.getWidth();
        int height = view.getHeight();
        int left = location[0];
        int top = location[1];
        int right = left + width;
        int bottom = top + height;

        Rect rect = new Rect(left, top, right, bottom);
        boolean contains = rect.contains(eventX, eventY);
        return contains;
    }
}

Related Tutorials