By setting OnClickListener on this view, all of this will be clickable (but not limited to your bitmap). To verify that the user clicked only the bitmap, you must override onTouchEvent (the MotionEvent event) and check if the touch coordinates match the bitmap.
@Override public boolean onTouchEvent(MotionEvent event) { float x = event.getX(); float y = event.getY(); switch(event.getAction()) { case MotionEvent.ACTION_DOWN:
Just replace bitmapXPosition and bitmapYPosition with the coordinates that you use to draw the bitmap, and bitmapWidth and bitmapHeight with the width and height that you use for drawing.
Also try not to allocate memory (create objects) inside the onDraw () method of any kind. This is bad for execution.
EDIT
private Rect r; private Paint paint; Bitmap bitmap; public TestRect(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); paint = new Paint(); paint.setColor(Color.BLUE); r = new Rect(); bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher); } public TestRect(Context context, AttributeSet attrs) { super(context, attrs); paint = new Paint(); paint.setColor(Color.BLUE); r = new Rect(); bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher); } public TestRect(Context context) { super(context); paint = new Paint(); paint.setColor(Color.BLUE); r = new Rect(); bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher); } @Override public void onDraw(Canvas c) { r.set(getWidth()/2, getHeight()/2, getWidth()/2 + 200, getHeight()/2 + 200);
By drawing a bitmap using Rect as the coordinates, you can check if the touch is inside the bitmap or not. Alternatively, instead of this large and ugly if statement, you can use
if(r.contains(x, y)) {
source share