How to set an onclick listener to a canvas?
android, android-canvas, java, onclicklistener
Solution
Might I suggest rethinking how this is going to work. If these rectangles are going to be buttons of some sort, perhaps your better off drawing buttons in your user interface, or using images instead of the rectangles. (Sorry didnt realise this is what you were going to do in your previous question)
Have a look at: Difference between a clickable ImageView and ImageButton
You can set an eventlistener on your imageview, as mentioned in another answer. See here: Image in Canvas with touch events
Problem
I have some rectangles drawn on `Canvas`. And now I need for each rectangle an `onclickListener`. But because I'm very new to android and specially `Canvas`, I need some help. Anyway is it possible to add a listener? It looks like this: And this is my code for it: ``` RelativeLayout ll = (RelativeLayout) findViewById(R.id.rect); Paint paint = new Paint(); Paint paintForSize = new Paint(); paintForSize.setColor(Color.parseColor("#FFFFFF")); paintForSize.setTextSize(45); Bitmap bg = Bitmap.createBitmap(480, 800, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bg); int left = 0; // initial start position of rectangles (50 pixels from left) int leftText =70; int topText = 93; int top = 50; // 50 pixels from the top int width = 60; int height = 60; for(int x = 0; x < 4; x++) { // draw 4 rectangles if(x == 0){ paint.setColor(Color.parseColor("#FF7979")); canvas.drawText("Rec 1", leftText, topText, paintForSize); } if(x == 1){ paint.setColor(Color.parseColor("#FFD060")); canvas.drawText("Rec 2", leftText, topText, paintForSize); } if(x == 2){ paint.setColor(Color.parseColor("#B6DB49")); canvas.drawText("Rec 3", leftText, topText, paintForSize); } if(x == 3){ paint.setColor(Color.parseColor("#CB97E5")); canvas.drawText("Rec 4", leftText, topText, paintForSize); } canvas.drawRect(left, top, left+width, top+height, paint); top = (top + height + 10); // set new left co-ordinate + 10 pixel gap topText = (topText + height + 10); } RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); params.addRule(RelativeLayout.ALIGN_PARENT_LEFT); ImageView iV = new ImageView(this); iV.setImageBitmap(bg); ll.addView(iV,params); ``` Can anybody guide me through this, how should I do it?