我使用此代码移动按钮。运动正在发生,但开始移动时按钮会向下滑动一点。 我也会在触摸时改变按钮的颜色。
public boolean onTouch(View view, MotionEvent event) {
float currX,currY;
int action = event.getAction();
Button gvup = (Button)findViewById(R.id.giveup);
gvup.setBackground(getResources().getDrawable(R.drawable.btn));
switch (action ) {
case MotionEvent.ACTION_DOWN: {
startClickTime = Calendar.getInstance().getTimeInMillis();
mPrevX = event.getX();
mPrevY = event.getY();
gvup.setBackground(getResources().getDrawable(R.drawable.btn1));
break;
}
case MotionEvent.ACTION_MOVE:
{
currX = event.getRawX();
currY = event.getRawY();
ViewGroup.MarginLayoutParams marginParams = new ViewGroup.MarginLayoutParams(view.getLayoutParams());
marginParams.setMargins((int)(currX - mPrevX), (int)(currY - mPrevY),0, 0);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(marginParams);
view.setLayoutParams(layoutParams);
gvup.setBackground(getResources().getDrawable(R.drawable.btn1));
break;
}
case MotionEvent.ACTION_CANCEL:
gvup.setBackground(getResources().getDrawable(R.drawable.btn1));
break;
case MotionEvent.ACTION_UP:
long clickDuration = Calendar.getInstance().getTimeInMillis() - startClickTime;
if(clickDuration < MAX_CLICK_DURATION) {
//click event has occurred
gvup.setBackground(getResources().getDrawable(R.drawable.btn));
giveUp();
}
break;
}
return true;
}
}
代码应该可以正常工作但不起作用。 如果代替
mPrevY = event.getY();
我输入
mPrevY = event.getY() + 65;
对于许多移动设备而言,移动位置正常,但不是全部,也不适用于标签。
感谢。
答案 0 :(得分:0)
尝试在ACTION_DOWN中使用event.getRawY() , event.getRawX()
代替event.getY() , event.getX()
。