Skip to content Skip to sidebar Skip to footer

Android: Only Make Certain Part Of Custom View Be Clickable

I have a custom view, assume it looks like this: I would like for my custom view to respond to the onClicks, however the catch is that I would like it to respond to the clicks ONL

Solution 1:

In a custom view, you handle clicks by overriding the onTouchEvent method of android's View class. First check that the location the user has clicked is within the circle. Then normally you would give some feedback on the MotionEvent.ACTION_DOWN event to let user know they have clicked, such as highlight the circle. Then on MotionEvent.ACTION_UP you can call your onClick method.

@Override
    public boolean onTouchEvent(MotionEvent event) {    
        boolean isTouchInCircle = checkTouchInCircle(event.getX(), event.getY());
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (isTouchInCircle) {
                    circleColor = highlightColor;
                    invalidate();
                }
                break;
            case MotionEvent.ACTION_MOVE:
                if (isTouchInCircle) {
                    circleColor = highlightColor;
                } else {
                    circleColor = normalColor
                }
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                if (isTouchInCircle) {
                    onClickCircle();
                }
                break;
        }
        return true;
    }

// Circle click zone approximated as a square
private boolean checkTouchInCircle(float touchX, float touchY) {
    if (touchX < circleCenterX + circleRadius
          && touchX > circleCenterX - circleRadius
          && touchY < circleCenterY + circleRadius
          && touchY > circleCenterY - circleRadius) {
        return true;
    } else {
        return false;
    }
}

Solution 2:

Unfortunately the answer Carson posted was not exactly what I was looking for as my example was only a simple one, with the reality sometimes it being a lot more difficult and checking the touch locations would be convoluted (imagine multiple views/shapes within the custom view being the click locations).

What I did was in the custom view do a find view by id on the elements of the custom view. Then I did setOnClickListener(this) on each element that I would like to be clicked able rather than on the whole view itself, so mCircle.setOnClickListener(this); and mInput.setOnClickListener(this);, then did implements View.OnClickListener for the custom view to handle the actions.


Post a Comment for "Android: Only Make Certain Part Of Custom View Be Clickable"