Is there an example of how to use a TouchDelegate in Android to increase the size of a view's click target?
AndroidAndroid Problem Overview
My understanding is that when you have a view that's too small to easily touch, you're supposed to use a TouchDelegate to increase the clickable region for that view.
However, searching for usage examples on Google turn up multiple people asking the question, but few answers.
Does anyone know the proper way to set up a touch delegate for a view to, say, increase its clickable region by 4 pixels in every direction?
Android Solutions
Solution 1 - Android
I asked a friend at Google and they were able to help me figure out how to use TouchDelegate. Here's what we came up with:
final View parent = (View) delegate.getParent();
parent.post( new Runnable() {
// Post in the parent's message queue to make sure the parent
// lays out its children before we call getHitRect()
public void run() {
final Rect r = new Rect();
delegate.getHitRect(r);
r.top -= 4;
r.bottom += 4;
parent.setTouchDelegate( new TouchDelegate( r , delegate));
}
});
Solution 2 - Android
I was able to accomplish this with multiple views (checkboxes) on one screen drawing largely from this blog post. Basically you take emmby's solution and apply it to each button and its parent individually.
public static void expandTouchArea(final View bigView, final View smallView, final int extraPadding) {
bigView.post(new Runnable() {
@Override
public void run() {
Rect rect = new Rect();
smallView.getHitRect(rect);
rect.top -= extraPadding;
rect.left -= extraPadding;
rect.right += extraPadding;
rect.bottom += extraPadding;
bigView.setTouchDelegate(new TouchDelegate(rect, smallView));
}
});
}
In my case I had a gridview of imageviews with checkboxes overlaid on top, and called the method as follows:
CheckBox mCheckBox = (CheckBox) convertView.findViewById(R.id.checkBox1);
final ImageView imageView = (ImageView) convertView.findViewById(R.id.imageView1);
// Increase checkbox clickable area
expandTouchArea(imageView, mCheckBox, 100);
Working great for me.
Solution 3 - Android
This solution was posted by @BrendanWeinstein in comments.
Instead of sending a TouchDelegate
you can override getHitRect(Rect)
method of your View
(in case that you are extending one).
public class MyView extends View { //NOTE: any other View can be used here
/* a lot of required methods */
@Override
public void getHitRect(Rect r) {
super.getHitRect(r); //get hit Rect of current View
if(r == null) {
return;
}
/* Manipulate with rect as you wish */
r.top -= 10;
}
}
Solution 4 - Android
emmby's approch didn't work for me but after a little changes it did:
private void initApplyButtonOnClick() {
mApplyButton.setOnClickListener(onApplyClickListener);
final View parent = (View)mApplyButton.getParent();
parent.post(new Runnable() {
@Override
public void run() {
final Rect hitRect = new Rect();
parent.getHitRect(hitRect);
hitRect.right = hitRect.right - hitRect.left;
hitRect.bottom = hitRect.bottom - hitRect.top;
hitRect.top = 0;
hitRect.left = 0;
parent.setTouchDelegate(new TouchDelegate(hitRect , mApplyButton));
}
});
}
Maybe it can save someone's time
Solution 5 - Android
According to @Mason Lee comment, this solved my problem. My project had relative layout and one button. So parent is -> layout and child is -> a button.
Here is a google link example google code
In case of deleting his very valuable answer I put here his answer.
> I was recently asked about how to use a TouchDelegate. I was a bit rusty myself on this and I couldn't find any good documentation on it.
> Here's the code I wrote after a little trial and error.
> touch_delegate_view is a simple RelativeLayout with the id
> touch_delegate_root. I defined with a single, child of the layout, the
> button delegated_button. In this example I expand the clickable area
> of the button to 200 pixels above the top of my button.
>
> public class TouchDelegateSample extends Activity {
>
> Button mButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
> super.onCreate(savedInstanceState);
> setContentView(R.layout.touch_delegate_view);
> mButton = (Button)findViewById(R.id.delegated_button);
> View parent = findViewById(R.id.touch_delegate_root);
>
> // post a runnable to the parent view's message queue so its run after
> // the view is drawn
> parent.post(new Runnable() {
> @Override
> public void run() {
> Rect delegateArea = new Rect();
> Button delegate = TouchDelegateSample.this.mButton;
> delegate.getHitRect(delegateArea);
> delegateArea.top -= 200;
> TouchDelegate expandedArea = new TouchDelegate(delegateArea, delegate);
> // give the delegate to an ancestor of the view we're delegating the
> // area to
> if (View.class.isInstance(delegate.getParent())) {
> ((View)delegate.getParent()).setTouchDelegate(expandedArea);
> }
> }
> });
}
}
>
> Cheers, Justin Android Team @ Google
Few words from me: if you want expand left side you give value with minus, and if you want expand right side of object, you give value with plus. This works the same with top and bottom.
Solution 6 - Android
Isn't it the better Idea of giving Padding to that particular component(Button).
Solution 7 - Android
A bit late to the party, but after much research, I'm now using:
/**
* Expand the given child View's touchable area by the given padding, by
* setting a TouchDelegate on the given ancestor View whenever its layout
* changes.
*/*emphasized text*
public static void expandTouchArea(final View ancestorView,
final View childView, final Rect padding) {
ancestorView.getViewTreeObserver().addOnGlobalLayoutListener(
new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
TouchDelegate delegate = null;
if (childView.isShown()) {
// Get hitRect in parent's coordinates
Rect hitRect = new Rect();
childView.getHitRect(hitRect);
// Translate to ancestor's coordinates
int ancestorLoc[] = new int[2];
ancestorView.getLocationInWindow(ancestorLoc);
int parentLoc[] = new int[2];
((View)childView.getParent()).getLocationInWindow(
parentLoc);
int xOffset = parentLoc[0] - ancestorLoc[0];
hitRect.left += xOffset;
hitRect.right += xOffset;
int yOffset = parentLoc[1] - ancestorLoc[1];
hitRect.top += yOffset;
hitRect.bottom += yOffset;
// Add padding
hitRect.top -= padding.top;
hitRect.bottom += padding.bottom;
hitRect.left -= padding.left;
hitRect.right += padding.right;
delegate = new TouchDelegate(hitRect, childView);
}
ancestorView.setTouchDelegate(delegate);
}
});
}
This is better than the accepted solution because it also allows a TouchDelegate to be set on any ancestor View, not just the parent View.
Unlike the accepted solution, it also updates the TouchDelegate whenever there is a change in the ancestor View's layout.
Solution 8 - Android
If don't want to do it programatically then simply create transparent area around the image, If you are using image as background for the button (view).
The grey area can be transparent to increase the touch area.
Solution 9 - Android
In most cases, you can wrap the view that requires a larger touch area in another headless view (artificial transparent view) and add padding/margin to the wrapper view and attach the click/touch even to the wrapper view instead of the original view that has to have a larger touch area.
Solution 10 - Android
To expand the touch area generically with pretty few restrictions use the following code.
It lets you expand the touch area of the given view
within the given ancestor
view by the given expansion
in pixels. You can choose any ancestor as long as the given view is in the ancestors layout tree.
public static void expandTouchArea(final View view, final ViewGroup ancestor, final int expansion) {
ancestor.post(new Runnable() {
public void run() {
Rect bounds = getRelativeBounds(view, ancestor);
Rect expandedBounds = expand(bounds, expansion);
// LOG.debug("Expanding touch area of {} within {} from {} by {}px to {}", view, ancestor, bounds, expansion, expandedBounds);
ancestor.setTouchDelegate(new TouchDelegate(expandedBounds, view));
}
private Rect getRelativeBounds(View view, ViewGroup ancestor) {
Point relativeLocation = getRelativeLocation(view, ancestor);
return new Rect(relativeLocation.x, relativeLocation.y,
relativeLocation.x + view.getWidth(),
relativeLocation.y + view.getHeight());
}
private Point getRelativeLocation(View view, ViewGroup ancestor) {
Point absoluteAncestorLocation = getAbsoluteLocation(ancestor);
Point absoluteViewLocation = getAbsoluteLocation(view);
return new Point(absoluteViewLocation.x - absoluteAncestorLocation.x,
absoluteViewLocation.y - absoluteAncestorLocation.y);
}
private Point getAbsoluteLocation(View view) {
int[] absoluteLocation = new int[2];
view.getLocationOnScreen(absoluteLocation);
return new Point(absoluteLocation[0], absoluteLocation[1]);
}
private Rect expand(Rect rect, int by) {
Rect expandedRect = new Rect(rect);
expandedRect.left -= by;
expandedRect.top -= by;
expandedRect.right += by;
expandedRect.bottom += by;
return expandedRect;
}
});
}
Restrictions that apply:
- The touch area can not exceed the bounds of the view's ancestor since the ancestor must be able to catch the touch event in order to forward it to the view.
- Only one
TouchDelegate
can be set to aViewGroup
. If you want to work with multiple touch delegates, choose different ancestors or use a composing touch delegate like explained in https://stackoverflow.com/questions/6799066/how-to-use-multiple-touchdelegate.
Solution 11 - Android
Because I didn't like the idea of waiting for the layout pass just to get the new size of the TouchDelegate's rectangle, I went for a different solution:
public class TouchSizeIncreaser extends FrameLayout {
public TouchSizeIncreaser(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
return true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
final View child = getChildAt(0);
if(child != null) {
child.onTouchEvent(event);
}
return true;
}
}
And then, in a layout:
<ch.tutti.ui.util.TouchSizeIncreaser
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp">
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
</ch.tutti.ui.util.TouchSizeIncreaser>
The idea is that TouchSizeIncreaser FrameLayout will wrap the Spinner (could be any child View) and forward all the touch events captured in it's hit rect to the child View. It works for clicks, the spinner opens even if clicked outside its bounds, not sure what are the implications for other more complex cases.