Reputation: 548
i'm new in android development. I wanted to set onTouchEvent particularly for an image. so that i can do some work ,like increase score etc....
Here is the sample code i tried..
@Override
protected void onDraw(Canvas canvas)
{
canvas.drawBitmap(image1, random.nextInt(455), random.nextInt(270), paint);
canvas.drawText("SCORE = "+score, 10, 20, paint);
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
// TODO Auto-generated method stub
if(toggelFlag)
{
score = score+10;
}
return super.onTouchEvent(event);
}
Actually i wanted to increase the score once i touch the image only. But here if i touch anywhere in the screen its increase the score. I want it for image only.
Upvotes: 2
Views: 4805
Reputation: 1809
Create a Region object with the image bounds like this:
Region region = new Region(left, top, right, bottom);
left, top, right and bottom define the image bounds.
Then, when you handle a touch event check if region contains the event position. Would be:
public boolean onTouchEvent(MotionEvent event)
{
float x = event.getX();
float y = event.getY();
if(region.contains((int)x, (int)y))
{
// touch in image
}
return super.onTouchEvent(event);
}
Upvotes: 4
Reputation: 5750
Try this one... Set onTouch listener to imageview...
1.Take on Linearlayout and add child like this
linear.addView(new CustomImage(this));
linear.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return true;
}
});
2.CustomImage extens view ,Your onDraw method is in this class should be like this.
private CustomImage extends View
{
@Override
protected void onDraw(Canvas canvas)
{
canvas.drawBitmap(image1, random.nextInt(455), random.nextInt(270), paint);
canvas.drawText("SCORE = "+score, 10, 20, paint);
}
Upvotes: 0