1 /* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-
2  * This Source Code Form is subject to the terms of the Mozilla Public
3  * License, v. 2.0. If a copy of the MPL was not distributed with this
4  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 
6 package org.mozilla.gecko.util;
7 
8 import android.graphics.Rect;
9 import android.view.TouchDelegate;
10 import android.view.View;
11 
12 import org.mozilla.gecko.R;
13 import org.mozilla.gecko.widget.TouchDelegateWithReset;
14 
15 public class TouchTargetUtil {
16     /**
17      * Ensures that a given targetView has a large enough touch area to ensure it can be selected.
18      * A TouchDelegate will be added to the enclosingView as necessary.
19      *
20      * @param targetView
21      * @param enclosingView
22      */
ensureTargetHitArea(final View targetView, final View enclosingView)23     public static void ensureTargetHitArea(final View targetView, final View enclosingView) {
24         enclosingView.post(new Runnable() {
25             @Override
26             public void run() {
27                 Rect delegateArea = new Rect();
28                 targetView.getHitRect(delegateArea);
29 
30                 final int targetHitArea = enclosingView.getContext().getResources().getDimensionPixelSize(R.dimen.touch_target_size);
31 
32                 final int widthDelta = (targetHitArea - delegateArea.width()) / 2;
33                 delegateArea.right += widthDelta;
34                 delegateArea.left -= widthDelta;
35 
36                 final int heightDelta = (targetHitArea - delegateArea.height()) / 2;
37                 delegateArea.bottom += heightDelta;
38                 delegateArea.top -= heightDelta;
39 
40                 if (heightDelta <= 0 && widthDelta <= 0) {
41                     return;
42                 }
43 
44                 TouchDelegate touchDelegate = new TouchDelegateWithReset(delegateArea, targetView);
45                 enclosingView.setTouchDelegate(touchDelegate);
46             }
47         });
48     }
49 }
50