---
title: "【Android自定义控件】一个简单的长按控件，用以解决长按多次触发点击事件"
author: "benson37"
date: "2014-10-09T18:13:55Z"
tags: []
categories: ["移动开发"]
slug: "android"
draft: false
lastmod: "2014-10-09T18:13:55Z"
id: 2126790
url: "https://benson37.iteye.com/blog/2126790"
---

项目中需要实现长按view多次一直触发点击事件，直到手指抬起；

开始是在业务层实现这些功能的，做完发觉是否可以自定义控件的形式，与业务分离，就写了个控件，简单重构了代码

```
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;

/**
 * 该控件用以实现长按触发多次点击事件的效果
 * 
 * @author Sanji.Shen
 *
 */
public class LongClickImageView extends ImageView {

	/**
	 * 长按事件触发频率
	 */
	private long mDelayMillis = 100;

	private boolean isMotionEventUp = true;

	public LongClickImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
		intiListener();
	}

	public LongClickImageView(Context context) {
		super(context);
		intiListener();
	}

	public LongClickImageView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		intiListener();
	}

	public void intiListener() {
		this.setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View v) {
				isMotionEventUp = false;
				mHandler.sendEmptyMessage(0);
				return false;
			}
		});
		this.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_UP) {
					isMotionEventUp = true;
				}
				return false;
			}
		});
	}

	/**
	 * 用以处理click事件
	 */
	Handler mHandler = new Handler(Looper.getMainLooper()) {
		public void handleMessage(android.os.Message msg) {
			if (!isMotionEventUp && isEnabled()) {
				// 调用click事件
				performClick();
				mHandler.sendEmptyMessageDelayed(0, mDelayMillis);
			}
		};
	};

	/**
	 * 设置触发时间间隔
	 * 
	 * @param delayMillis
	 */
	public void setmDelayMillis(long delayMillis) {
		this.mDelayMillis = delayMillis;
	}

}
```