I created a method for changing the position of an ImageView, based on the position of other Image.
public void move(double zx, double zy) {
RelativeLayout.LayoutParams params =
new RelativeLayout.LayoutParams(80,80);
// the imageView s was initialized in the onCreate()
System.out.println("working");
if (zx < s.getLeft()) {
if (s.getLeft() - zx > 0) {
params.leftMargin = s.getLeft() -1;
} else
params.leftMargin = s.getLeft() +1;
}
if (zx > s.getLeft()) {
if (s.getLeft() - zx > 0) {
params.leftMargin = s.getLeft() -1;
} else
params.leftMargin = s.getLeft() +1;
}
if (zy > s.getTop()) {
if (s.getTop() - zy > 0) {
params.topMargin = s.getTop() -1;
} else
params.topMargin = s.getTop() + 1;
}
if (zy < (int)s.getY()) {
if ((int)s.getY() - zy > 0) {
params.topMargin = s.getTop() -1;
} else
params.topMargin = s.getTop() + 1;
}
s.setLayoutParams(params);
}
Then I called in the onCreate()
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fase);
s = (ImageView)findViewById(R.id.s);
box = (ImageView)findViewById(R.id.box);
move(box.getLeft(),box.getTop());
}
The message "working" was printed, but only once. The imageview's position also didn't change. My conclusion is that the method wasn't executed repeatedly. Otherwise, the imageView's position would be changing every time, and the message "working" would appear each instant. How can I solve it? Should I call the method in other class? I tried to call it in a timertask and execute the timertask each milisecond, but tha application just stopped.
Drag command for the other ImageView (inside oncreate):
box.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
LayoutParams layoutParams = (LayoutParams) box.getLayoutParams();
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_MOVE:
System.out.println(box.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 - 250;
layoutParams.topMargin = y_cord - 300;
box.setLayoutParams(layoutParams);
break;
default:
break;
}
return true;
}
});