I have followed One of the video on YouTube that I can move image by pressing the image and move around, but the starting position is at the top left corner and I try to move it manually but still at the same position this is my code in my Activity.
Any help would be appreciated :)
public class Game extends AppCompatActivity {
private ImageView Plane;
private ViewGroup RootLayout;
private int _xDelta;
private int _yDelta;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
RootLayout = (ViewGroup)findViewById(R.id.main3);
Plane = (ImageView)RootLayout.findViewById(R.id.airplane);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(280, 280);
Plane.setLayoutParams(layoutParams);
Plane.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
final int X = (int) event.getRawX();
final int Y = (int) event.getRawY();
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) Plane.getLayoutParams();
_xDelta = X - lParams.leftMargin;
_yDelta = Y - lParams.topMargin;
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_POINTER_DOWN:
break;
case MotionEvent.ACTION_POINTER_UP:
break;
case MotionEvent.ACTION_MOVE:
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) Plane.getLayoutParams();
layoutParams.leftMargin = X - _xDelta;
layoutParams.topMargin = Y - _yDelta;
layoutParams.rightMargin = -250;
layoutParams.bottomMargin = -250;
Plane.setLayoutParams(layoutParams);
break;
}
RootLayout.invalidate();
return true;
}
});
}
}
It is about algorithm, I am writing Pseudo code, whatever the type of image:
int nScreenWidth = FuncSW();
int nScreenHeight= FuncSH();
int nImageWidth = FuncIW();
int nImageHeight = FuncIH();
SetImagePosition( nScreenWidth/2 - nImageWidth/2, nScreenHeight/2-nImageHeight/2 );
// SetImagePosition(xpos,ypos) where xpos is the image left pos, ypos is image the top pos