How to set an onclick listener to a canvas?

Viewed 15569

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:

enter image description here

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?

2 Answers
Related