Add Image to layout on touch in android with respect to touch position
android
Solution
I had same request and this is what i done and it worked perfectly for me
final RelativeLayout rr = (RelativeLayout) findViewById(R.id.rr);
rr.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
int x = (int) event.getX();
int y = (int) event.getY();
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
ImageView iv = new ImageView(getApplicationContext());
lp.setMargins(x, y, 0, 0);
iv.setLayoutParams(lp);
iv.setImageDrawable(getResources().getDrawable(
R.drawable.gr1));
((ViewGroup) v).addView(iv);
}
return false;
}
});
This will place image to RelativeLayout where you touched starting coordinates from there. If you want to center new image where you touched RelativeLayout you need to calculate Height and Width of your image and change one line in my code to
lp.setMargins(x - yourImageWidth/2, y - yourImageHeight/2, 0, 0);
Problem
Where ever i touch on the screen with respect to x y position i need to add one image on that particular position. I tried by implementing the ontouch listener but it is adding image to different position and many images are being appeared on many touch i want some thing like where ever i touch that same image should appear there Please Help i am new to android working on project in a compnay This is my activity code ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final RelativeLayout rl = (RelativeLayout) findViewById(R.id.wwcontainer); //Set On TouchListner to the Layout rl.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { Log.i("OnTouch", "On Touch View Group...."); int x = (int) event.getX(); int y = (int) event.getY(); ImageView imageView = new ImageView(getApplicationContext()); imageView.setImageResource(R.drawable.icon); imageView.setLayoutParams(new LayoutParams(x,y)); rl.addView(imageView); return true; } }); } ``` I know about drag and drop i dont want drag and drop instead i need touch any where there image should appear wrt touch position please help me