onClickListener in Canvas

2019-02-11 07:26发布

问题:

Im developing an application which having Images as a Index on selection of particular image that activity will begin but I dont know how to set onClickListener or onTouchListener in Canvas heres my code

public class DrawView extends View implements OnTouchListener {

LinearLayout mLayout;
Bitmap index;
Bitmap book;
Bitmap bird;
Bitmap game;
Bitmap mail;
Bitmap music;
Bitmap torch;
Paint paint;

public DrawView(Context context) {
    super(context);

    setFocusable(true);
    setFocusableInTouchMode(true);
    this.setOnTouchListener(this);

    index = BitmapFactory.decodeResource(getResources(), R.drawable.photo1);
    book = BitmapFactory.decodeResource(getResources(), R.drawable.book);
    game = BitmapFactory.decodeResource(getResources(), R.drawable.game);
    music = BitmapFactory.decodeResource(getResources(), R.drawable.music);
}

public void onDraw(Canvas canvas){
    paint = new Paint();
    Bitmap indexcanvas = Bitmap.createScaledBitmap(index, canvas.getWidth(),
                                                   canvas.getHeight(), true);
    canvas.drawBitmap(indexcanvas, 0, 0, paint);
    canvas.drawBitmap(book, 160, 100, paint);
    canvas.drawBitmap(game, 30, 10, paint);
    canvas.drawBitmap(music, 80, 50, paint);
} 

public boolean onTouch(View v, MotionEvent event) {
    return false;
}

Please if anyone knows how to add onClickListener for particular image e.g. here if I click on Book then bookActivity will start.

回答1:

try something like this:

public boolean onTouch(View v, MotionEvent event) {
   if((event.getX(0)>=160) && 
      (event.getY(0)>=100) && 
     ( event.getX(0)<=160+BOOK_IMG_WIDTH) && 
      (event.getY(0)<=100+BOOK_IMG_HEIGHT))
      {
          //book selected
      }
   return true;
}


回答2:

Use ImageView instead of bitmap and add it to your layout:

book = new ImageView(context);
book.setImageResource(R.drawable.book);
book.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            /*...*/
        }
    };);


回答3:

Save the images' coords in an ArrayList. Set OnClickListener on the context, get the point coords that has been clicked, find the image in the arraylist and do something :)