android 按钮点击1次,点击3次和点击6次触发不同的事件

今天做项目遇到按钮点击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+"次");

}



  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值