Reputation: 387
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.
Upvotes: 2
Views: 13312
Reputation: 3812
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;
}
Upvotes: 5
Reputation: 4187
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 :)
Upvotes: 0
Reputation: 59158
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) {
/*...*/
}
};);
Upvotes: 0