I created an ImageView that I can drag over the screen. But sometimes it goes out of the screen, and I am trying to solve it. How can I define minimum and maximum limits fot the x and y coordinates of the imageview?
I tried this, but failed:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fase);
final ImageView balls = (ImageView)findViewById(R.id.ball);
LayoutParams layoutParams = (LayoutParams) balls.getLayoutParams();
changeScreen = (Button)findViewById(R.id.button);
changeScreen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent Ts2 = new Intent(Fase.this, Over.class);
Fase.this.startActivity(Ts2);
Fase.this.finish();
}
});
if (balls.getLeft()<400)
{
layoutParams.leftMargin = 400;
}
if (balls.getLeft() > 500)
{
layoutParams.leftMargin = 500;
}
if (balls.getTop() <40)
{
layoutParams.topMargin = 40;
}
if (balls.getTop() > 500)
{
layoutParams.topMargin = 500;
}
windowwidth = getWindowManager().getDefaultDisplay().getWidth();
windowheight = getWindowManager().getDefaultDisplay().getHeight();
balls.setOnTouchListener(new View.OnTouchListener() { // this allows me to drag the imageView
@Override
public boolean onTouch(View v, MotionEvent event) {
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) fish.getLayoutParams();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_MOVE:
System.out.println(balls.getLeft());
int x_cord = (int) event.getRawX();
int y_cord = (int) event.getRawY();
if (x_cord > windowwidth) {
x_cord = windowwidth;
}
if (y_cord > windowheight) {
y_cord = windowheight;
}
layoutParams.leftMargin = x_cord - 50;
layoutParams.topMargin = y_cord - 150;
balls.setLayoutParams(layoutParams);
break;
default:
break;
}
return true;
}
});
}
- OBS: this part of the code is in the "onCreate" method. Is it a problem?