今天做项目遇到按钮点击1次,点击3次和点击6次触发不同的事件的需求,仔细研究了一下,特把成果记录于此。
如下图:下面一列按钮都要有项目需求的功能
步骤如下:
1. Activity 继承OnClickListener 覆写OnClick(View v)方法 并调用clickEvent(final int id);
2.自定义法clickEvent(final int id),该方法会做连续点击的按钮是否是同一个按钮的判断
并构造定时器,每500ms执行一次监听点击次数,并在需要的点击次数时发送handler信息
3.handler里对点击事件做统一处理
代码如下:
clickEvent(final int id)方法:
</pre><pre name="code" class="java"> int clickCount = 0;
Timer timer;
TimerTask mTimerTask;
int viewId =0;
@SuppressWarnings("unused")
public void clickEvent(final int id){
if(viewId==0){
viewId = id;
}else
if(viewId!=id){//点击的不是同一个按钮,则一切清零重头开始
clickCount = 0;
mTimerTask.cancel();
timer.cancel();
mTimerTask=null;
timer = null;
viewId = 0;
clickEvent(id);
return;
}
clickCount++;
if(timer!=null){
return;
}
timer = new Timer();
mTimerTask = new TimerTask() {
int count =0;
@Override
public void run() {
//500ms之后若点击次数发生改变则更新点击次数,否则显示点击次数,定时结束并一切清零
if(count!=clickCount){
count = clickCount;
}else{
Message msg = Message.obtain();
msg.obj = viewId;
if(count ==1){
msg.what = 1;
handler_click.sendMessage(msg);
}else if(count == 3){
msg.what = 3;
handler_click.sendMessage(msg);
//
}else if(count == 6){
msg.what = 6;
handler_click.sendMessage(msg);
//
}
clickCount = 0;
this.cancel();
timer.cancel();
mTimerTask=null;
timer = null;
viewId = 0;
}
}
};
timer.schedule(mTimerTask, 500, 500);
}
</pre><pre name="code" class="java">Handler handler_click = new Handler(){
@Override
public void dispatchMessage(Message msg) {
super.dispatchMessage(msg);
int id = (Integer) msg.obj;
int cc = msg.what;
showToast("点击"+cc+"次");
}