我写了一个按钮的所有代码,可以通过手指按下移动或拖动,现在我也希望该按钮在点击时执行某些操作(例如,在我的情况下点击进入网站) ) 我在一个单独的类中实现了所有代码,如下所示:
public class MultiTouchListener implements OnTouchListener
{
private float mPrevX;
private float mPrevY;
public MainActivity mainActivity;
public MultiTouchListener(MainActivity mainActivity1) {
mainActivity = mainActivity1;
}
@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();
MarginLayoutParams marginParams = new 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;
}
}
我在此主要活动中将其称为
MultiTouchListener touchListener=new MultiTouchListener(this);
onButton.setOnTouchListener(touchListener);
可移动的拖放按钮工作正常,我只想按下此按钮打开网站链接,我必须在我的代码中进行哪些更改才能执行此操作.Thankyou。
答案 0 :(得分:2)
在onTouchListener中的ACTION_UP
下,您必须手动调用view.performClick()
。这将触发您的onclick监听器,然后您可以使用它来打开您的网页。
这样的事情:
case MotionEvent.ACTION_UP:
view.performClick();
break;
然后
onButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//do stuff
}
});
修改强>
嗯。显然这样做会淹没它的拖放方面。请尝试这样做(来自here并为您的班级稍作修改。)
在你的ontouch课程中:
//create a gesturedetector
private GestureDetector gestureDetector = new GestureDetector(this, new SingleTapConfirm());
@Override
public boolean onTouch(View view, MotionEvent event) {
//...etc
switch (action ) {
if (gestureDetector.onTouchEvent(view)) {
// this is a "click", put your click event here
return true;
} else {
//your original touch drag and drop code should go here
case MotionEvent.ACTION_DOWN: {
//...
}
case MotionEvent.ACTION_MOVE:
{
//...
break;
}
//etc
}
}
return false;
}
private class SingleTapConfirm extends SimpleOnGestureListener {
@Override
public boolean onSingleTapConfirmed(MotionEvent event) {
return true;
}
}
}
有了这个,你就不再需要一个onclick监听器了。看看是否有效。