I have a program in which I would like to place an image at the coordinates of a touch event. I have the coordinates now I just need help with placing an image there. I will
Drawable recycle_bin = context.getResources().getDrawable(android.R.drawable.ic_menu_delete);
int w = recycle_bin.getIntrinsicWidth();
int h = recycle_bin.getIntrinsicHeight();
int x = getWidth()/2 - w/2;
int y = getHeight() - h - 5;
recycle_bin.setBounds( x, y, x + w, y + h );
recycle_bin.draw( canvas );
that's how I draw a recycle bin icon at the bottom center
place the image you want on top in the xml of your application. set it invisible or gone...
replace:
final View touchView2 = findViewById(R.id.ImageView02);
before the classes constructor:
ImageView touchView2;
and in the constructor (onCreate) method
touchView2 = (ImageView) findViewById(R.id.ImageView02);
Now set up a onTouchEventListener by getting all touches on the screen. If those coordinates are in a position you like call the placeImage method with the pressed X and Y coordinate. this method is placed outside the class constructor (onCreate) so first method below should be right:
@Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);
int eventAction = event.getAction();
switch(eventAction) {
case MotionEvent.ACTION_DOWN:
float TouchX = event.getX();
float TouchY = event.getY();
placeImage(TouchX, TouchY);
break;
}
return true;
}
now the placeImage method:
private void placeImage(float X, float Y) {
int touchX = (int) X;
int touchY = (int) Y;
// placing at bottom right of touch
touchView2.layout(touchX, touchY, touchX+48, touchY+48);
//placing at center of touch
int viewWidth = touchView2.getWidth();
int viewHeight = touchView2.getHeight();
viewWidth = viewWidth / 2;
viewHeight = viewHeight / 2;
touchView2.layout(touchX - viewWidth, touchY - viewHeight, touchX + viewWidth, touchY + viewHeight);
}
This should be your answer... now you only have to make touchView visible:
touchView2.setVisibility(0);
To place a image at a certain coordinates you will have to draw the image on the canvas . To get the coordinates of the touch event use the following code:
@Override
public void onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_MOVE) {
mTouchX = event.getX();
mTouchY = event.getY();//stores touch event
} else {
mTouchX = -1;
mTouchY = -1;
}
super.onTouchEvent(event);
}