-1

Here is the main Java file. Problem arises when i try to use setX and setY, the image is shifted to left and to bottom and moves relative to touch but not on the touch position.

public class MainActivity extends AppCompatActivity {

public ImageView imageView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    imageView = findViewById(R.id.imgv);
    imageView.setImageResource(R.drawable.pawn);
    imageView.setScaleX((float) 0.1);
    imageView.setScaleY((float) 0.1);
    imageView.setX((float)0);
    imageView.setY((float)0);
}
public void update(float x,float y) {
    imageView.setX(x);
    imageView.setY(y);
}
@Override
public boolean onTouchEvent(MotionEvent e) {
    float x = e.getX();
    float y = e.getY();
    update(x,y);
    return true;
}
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
vasu tomar
  • 23
  • 1
  • 6
  • If you want to drag view on touch events, follow this https://stackoverflow.com/a/31094315/7967905 – SafalFrom2050 Jun 25 '18 at 17:19
  • @SafalSharma i don't want to drag, i want to re-position it on a new touch. But i cannot do it, it appears at a different position. – vasu tomar Jun 25 '18 at 17:30

1 Answers1

1

I suspect that e.getX() and e.getY() give you the difference in movement, not the absolute values for X and Y. Add them to the current position:

public void update(float x,float y) {
  imageView.setX(imageView.getX()+x);
  imageView.setY(imageView.getY()+y);
}
f1sh
  • 11,489
  • 3
  • 25
  • 51