有一个控件,既支持拖动又需要支持点击事件,当使用ontouch事件,可以实现拖动,但这时候当up的时候,就会同时相应点击事件,当现在的需求是拖动的时候不能响应点击事件,找到如下方法:
1.设置一个全局的变量isclick,默认为false,当ontouch中down时,重新设为false,当move的时候设置为false,接着就进入up的方法里面,如果此时可以对时间进行判断,当判断从点击到移动的时间超过500ms的话,就不应该响应点击事件,设置isclick为true,也就是消费此事件,不接着让点击事件响应,如下代码:
package com.oppo.examples;
import android.app.Activity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class DraftTest extends Activity implements OnTouchListener {
/** Called when the activity is first created. */
int screenWidth;
int screenHeight;
int lastX;
int lastY;
private long startTime = 0;
private long endTime = 0;
private boolean isclick;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DisplayMetrics dm = getResources().getDisplayMetrics();
screenWidth = dm.widthPixels;
screenHeight = dm.heightPixels - 50;
Button button = (Button) findViewById(R.id.btn);
ImageView imageView = (ImageView) findViewById(R.id.btn2);
imageView.setOnTouchListener(this);
button.setOnTouchListener(this);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Toast.makeText(DraftTest.this, "点击和拖动并存", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
lastX = (int) event.getRawX();
lastY = (int) event.getRawY();
isclick = false;//当按下的时候设置isclick为false,具体原因看后边的讲解
startTime = System.currentTimeMillis();
System.out.println("执行顺序down");
break;
/**
* layout(l,t,r,b) l Left position, relative to parent t Top position,
* relative to parent r Right position, relative to parent b Bottom
* position, relative to parent
* */
case MotionEvent.ACTION_MOVE:
System.out.println("执行顺序move");
isclick = true;//当按钮被移动的时候设置isclick为true
int dx = (int) event.getRawX() - lastX;
int dy = (int) event.getRawY() - lastY;
int left = v.getLeft() + dx;
int top = v.getTop() + dy;
int right = v.getRight() + dx;
int bottom = v.getBottom() + dy;
if (left < 0) {
left = 0;
right = left + v.getWidth();
}
if (right > screenWidth) {
right = screenWidth;
left = right - v.getWidth();
}
if (top < 0) {
top = 0;
bottom = top + v.getHeight();
}
if (bottom > screenHeight) {
bottom = screenHeight;
top = bottom - v.getHeight();
}
v.layout(left, top, right, bottom);
lastX = (int) event.getRawX();
lastY = (int) event.getRawY();
break;
case MotionEvent.ACTION_UP:
endTime = System.currentTimeMillis();
//当从点击到弹起小于半秒的时候,则判断为点击,如果超过则不响应点击事件
if ((endTime - startTime) > 0.1 * 1000L) {
isclick = true;
} else {
isclick = false;
}
System.out.println("执行顺序up");
break;
}
return isclick;
}
}