onClickListener in Canvas

2019-02-11 07:03发布

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.

3条回答
不美不萌又怎样
2楼-- · 2019-02-11 07:33

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 :)

查看更多
手持菜刀,她持情操
3楼-- · 2019-02-11 07:38

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) {
            /*...*/
        }
    };);
查看更多
欢心
4楼-- · 2019-02-11 07:51

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;
}
查看更多
登录 后发表回答