2011-06-24 44 views
1

我写了一个代码来移动拖动按钮。我正在更新基于当前鼠标坐标的按钮X和Y坐标,但是当我拖动按钮时,即使拖动速度很慢,鼠标坐标值也会在低值和高值之间切换。在ACTION_MOVE上切换坐标

当我记录的坐标值显示:

(70, 24) - (15, 36) - (86, 51) - (20, 48) - (90, 54) - (32, 60) - (102, 66) ... 

正如你可以看到,他们是高值和低值之间切换,甚至当我在一个方向上非常缓慢拖动。谁能告诉我为什么?

这里是我的代码:

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; 
} 

} 

回答

1

我没有你的代码测试,但我有过类似的事情发生在我身上了过去。

getX()和getY()函数返回相对于您的Button的值。由于您要更改onTouchListener中的按钮位置,因此还要更改getX()和getY()所基于的坐标系。

尝试使用getRawX()和getRawY()代替。这些函数独立于Button的位置,不应该给你交替的值。

+0

非常感谢!那样做了! –

+1

我很高兴能帮上忙!是否有足够的帮助来赚取赏金? – theisenp

+0

当然,我疯了。我很久以前就已经发布了这个问题,但没有人能够指出我正确的方向。非常感谢你的帮助。 –