每当设置一个可移动的按钮时,它就变得不可点击了。 我可以移动按钮但是通过按钮单击调用的功能不起作用。 我在xml文件中设置了android:onClick =“playGame”,并在类中定义了playGame函数。但它不起作用。
如果我删除为可移动按钮编写的代码,它的工作正常。
为可移动按钮编写的代码是
@Override
public boolean onTouch(View view, MotionEvent event) {
float currX,currY;
int action = event.getAction();
switch (action ) {
case MotionEvent.ACTION_DOWN: {
mPrevX = event.getX();
mPrevY = event.getY();
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);
break;
}
case MotionEvent.ACTION_CANCEL:
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
代码可以正常移动按钮,但按钮变得无法点击。
答案 0 :(得分:0)
我认为您应该将移动与onTouchEvent()
中的点击区分开来:
@Override
public boolean onTouch(View view, MotionEvent event) {
private static final int MAX_CLICK_DURATION = 200;//!!
private long startClickTime; //!!
...
switch (action ) {
case MotionEvent.ACTION_DOWN: {
startClickTime = Calendar.getInstance().getTimeInMillis();//!!
...
}
case MotionEvent.ACTION_MOVE:
{
...
}
case MotionEvent.ACTION_CANCEL:
break;
case MotionEvent.ACTION_UP:
long clickDuration = Calendar.getInstance().getTimeInMillis() - startClickTime;
if(clickDuration < MAX_CLICK_DURATION) {
//click event has occurred
}
break;
}
return true;
}
答案 1 :(得分:0)
您可以使用手势检测器来分离逻辑。
GestureDetector gestureDetector = new GestureDetector(this,new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent event) {
return true;
}
});
your_button_view.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
if (gestureDetector.onTouchEvent(arg1)) {
// single tap
return true;
} else {
// your code for move and drag
}
return false;
}
});