1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.documentsui.ui;
18 
19 import android.graphics.Rect;
20 import android.view.MotionEvent;
21 import android.view.View;
22 import android.view.ViewGroup;
23 import android.view.ViewParent;
24 
25 /**
26  * A utility class for working with Views.
27  */
28 public final class Views {
29 
Views()30     private Views() {}
31 
32     /**
33      *
34      * Return whether the event is in the view's region. We determine it with in the coordinate
35      * of the parent view that dispatches the motion event.
36      * @param event the motion event
37      * @param eventSource the view dispatching the motion events.
38      * @param view the view to check the selection region
39      * @return True, if the event is in the region. Otherwise, return false.
40      */
41 
isEventOver(MotionEvent event, ViewParent eventSource, View view)42     public static boolean isEventOver(MotionEvent event, ViewParent eventSource, View view) {
43         if (view == null || event == null || !view.isAttachedToWindow()) {
44             return false;
45         }
46 
47         View parent = null;
48         if (eventSource instanceof ViewGroup) {
49             parent = (View) eventSource;
50         }
51 
52         final Rect viewBoundsOnGlobalCoordinate = getBoundsOnScreen(view);
53 
54         // If the parent is null, it means view is the view root of the window, so the event
55         // should be from view itself, in this case we don't need any offset.
56         final int[] viewParentCoord = new int[2];
57         if (parent != null) {
58             parent.getLocationOnScreen(viewParentCoord);
59         }
60 
61         Rect viewBoundsOnParentViewCoordinate = new Rect(viewBoundsOnGlobalCoordinate);
62         viewBoundsOnParentViewCoordinate.offset(-viewParentCoord[0], -viewParentCoord[1]);
63         return viewBoundsOnParentViewCoordinate.contains((int) event.getX(), (int) event.getY());
64     }
65 
getBoundsOnScreen(View view)66     private static Rect getBoundsOnScreen(View view) {
67         final int[] coord = new int[2];
68         view.getLocationOnScreen(coord);
69 
70         return new Rect(coord[0], coord[1], coord[0] + view.getMeasuredWidth(),
71                 coord[1] + view.getMeasuredHeight());
72     }
73 }
74