degant
degant

Reputation: 4981

Android Listener on canvas?

I just got started with Android and I was wondering how to use listeners in a canvas. Particularly as part of my project, the objective is for an event to occur when we drag click from one point to another. The concept is from a game called brainvita. The game need not be understood to answer my question. All I want to know is the simplest way to make a listener for the drag clicks from one point to another on the canvas?

Do I need to map the canvas to a grid and have multiple listeners? What is the simplest way?

Additionally I'm attaching the code of the game developed so far, just the basics that help in displaying the grid!

package com.project.android.brainvita;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;

public class GameView extends View {

Paint paint = new Paint();
Paint paintF = new Paint();
Paint paintG = new Paint();
int width, height;
int MARGIN = 4;
int MARGIN_BIG = 10;
int sx = 2;

public GameView(Context context) {
    super(context);
    paint.setColor(Color.WHITE);
    paintF.setColor(Color.rgb(40, 60, 204));
    paintG.setColor(Color.rgb(240, 30, 20));
}

public void onDraw(Canvas canvas) {
    // Draw external circle
    canvas.drawCircle(width / 2, height / 2, (width - MARGIN) / 2, paintF);

    // Calculate radius of small circles
    int radius = (width - MARGIN_BIG*2) / 14;

    // Draw grid
    for (int j = -3; j <= 3; j++) {
        if (j >= -1 && j <= 1)
            for (int i = -3; i <= 3; i++) {
                canvas.drawCircle(width / 2 + (2 * radius * i), height / 2
                        + (2 * radius * j), radius - sx, paint);
            }
        else
            for (int i = -1; i <= 1; i++) {
                canvas.drawCircle(width / 2 + (2 * radius * i), height / 2
                        + (2 * radius * j), radius - sx, paint);
            }
    }
}

protected void onSizeChanged(int w, int h, int ow, int oh) {
    width = w;
    height = h;
}

}

Upvotes: 0

Views: 1635

Answers (1)

Nick Campion
Nick Campion

Reputation: 10479

In android development, a canvas is used for drawing. A view is used for interacting with the user. There isn't a direct mechanism for a canvas to receive user input. This must be handled through a view.

You'll want to add an onTouchListener to the View that is hosting your canvas and use that listener to store state information about touches from the user.

Upvotes: 1

Related Questions