AI智能
改变未来

android OnTouchListener OnClickListener实现单击和双击

钉钉、微博极速扩容黑科技,点击观看阿里云弹性计算年度发布会!>>>

package com.kaikeba.android.smallVideo.lisener;import android.os.Handler;import android.view.View;public class DoubleClickListener implements View.OnClickListener {//记录连续点击次数private int clickCount = 0;private Handler handler;private DoubleClickCallBack myClickCallBack;public interface DoubleClickCallBack {//点击一次的回调void oneClick(View view);//连续点击两次的回调void doubleClick(View view);}public DoubleClickListener(DoubleClickListener.DoubleClickCallBack myClickCallBack) {this.myClickCallBack = myClickCallBack;handler = new Handler();}@Overridepublic void onClick(View v) {clickCount++;//双击间二百毫秒延时int timeout = 200;handler.postDelayed(() -> {if (clickCount == 1) {myClickCallBack.oneClick(v);} else if (clickCount == 2) {myClickCallBack.doubleClick(v);}//清空handler延时,并防内存泄漏handler.removeCallbacksAndMessages(null);//计数清零clickCount = 0;}, timeout);//延时timeout后执行run方法中的代码}}
package com.kaikeba.android.smallVideo.lisener;import android.os.Handler;import android.util.Log;import android.view.MotionEvent;import android.view.View;public class DoubleTouchListener implements View.OnTouchListener {//记录连续点击次数private int clickCount = 0;private Handler handler;private DoubleClickCallBack myClickCallBack;private static final String TAG = \"DoubleTouchListener\";@Overridepublic boolean onTouch(View v, MotionEvent event) {int action = event.getAction();switch (action){case MotionEvent.ACTION_DOWN:break;case MotionEvent.ACTION_MOVE:break;case MotionEvent.ACTION_UP:float x= event.getX();float y= event.getY();Log.e(TAG, \"onTouch: \"+x+\"    y:\"+y );clickCount++;//双击间二百毫秒延时int timeout = 200;handler.postDelayed(() -> {if (clickCount == 1) {myClickCallBack.oneClick(v);} else if (clickCount == 2) {myClickCallBack.doubleClick(v,x,y);}//清空handler延时,并防内存泄漏handler.removeCallbacksAndMessages(null);//计数清零clickCount = 0;}, timeout);//延时timeout后执行run方法中的代码break;}return false;}public interface DoubleClickCallBack {//点击一次的回调void oneClick(View view);//连续点击两次的回调void doubleClick(View view,float x,float y);}public DoubleTouchListener(DoubleTouchListener.DoubleClickCallBack myClickCallBack) {this.myClickCallBack = myClickCallBack;handler = new Handler();}}

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » android OnTouchListener OnClickListener实现单击和双击