I want to build an app that has an imageview and it simply follows the finger touch. In other words, the imageview follows the touch of the finger. I have partially achieved this, in the sense that the imageview is following the touch of the finger but the problem is that it is at some offset. The imageview is about an inch down the actual touch.
Below is my code:
public class MainActivity extends AppCompatActivity {
ImageView img;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView)findViewById(R.id.img1);
img.setImageResource(R.drawable.ic_remove_circle_black_24dp);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
img.setX(event.getX());
img.setY(event.getY());
return false;
}
}
What could be the reason behind the offset?
Edit: Solution
Following code does what I need:
public class MainActivity extends AppCompatActivity {
ImageView img;
int[] viewCoords = new int[2];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView)findViewById(R.id.img1);
img.setImageResource(R.drawable.ic_remove_circle_black_24dp);
}
@Override
public boolean onTouchEvent(MotionEvent event){
img.getLocationOnScreen(viewCoords);
img.setX(event.getX()-(viewCoords[0]-img.getX()));
img.setY(event.getY()-(viewCoords[1]-img.getY()));
return true;
}
}
Thanks to Doomsknight for the direction.