I have written a code to move a button as it is dragged. I am updating the buttons X and Y coordinates based on the current mouse coordinates, but when I am dragging the button the mouse coordinate values are toggling between low and high values, even when I am dragging very slowly.
When I am logging the coordinates the values show as :
(70, 24) - (15, 36) - (86, 51) - (20, 48) - (90, 54) - (32, 60) - (102, 66) ...
As you can see, they are toggling between high and low values, even when I am dragging very slowly in one direction. Can anyone tell me why?
Here is my code :
public class MyFrames extends Activity implements View.OnTouchListener {
public Button moveable;
// public TextView log;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//changer = (Button) findViewById(R.id.btn_changer);
moveable = (Button) findViewById(R.id.btn_moveable);
moveable.setOnTouchListener(this);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch(event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_MOVE:
int x = (int)event.getX();
int y = (int)event.getY();
int w = moveable.getMeasuredWidth();
int h = moveable.getMeasuredHeight();
moveable.layout( x, y, x + w, y + h);
Log.v("Moveable", "X = " + x + " Y = " + y + "\n");
return true;
}
return false;
}
}
I haven’t tested it with your code, but I have had something similar happen to me in the past.
The getX() and getY() functions return values that are relative to your Button. Since you are changing the button’s position in the onTouchListener, you also change the coordinate system that getX() and getY() are based on.
Try using getRawX() and getRawY() instead. Those functions are independent of the Button’s position, and shouldn’t give you alternating values.