android自定义一组按钮,Android自定义按钮长按持续事件

有时候需要这种需求,按住按钮不放,0.1秒发送一次数据包,那么下面这个自定义按钮是最好的实例!import android.content.Context;

import android.util.AttributeSet;

import android.view.MotionEvent;

import android.widget.Button;

import com.fenjin.app.item.RobotButtonItem;

public class MButton extends Button {

private boolean clickdown = false;

private LongTouchListener mListener;

private int mtime;

public MButton(Context context, AttributeSet attrs) {

super(context, attrs);

// TODO Auto-generated constructor stub

}

@Override

public boolean onTouchEvent(MotionEvent event) {

if (event.getAction() == MotionEvent.ACTION_DOWN) {

clickdown = true;

if (mListener != null)

new LongTouchThread().start();

} else if (event.getAction() == MotionEvent.ACTION_UP

|| event.getAction() == MotionEvent.ACTION_CANCEL) {

clickdown = false;

}

return true;

}

/**

* 处理长按的任务

*/

class LongTouchThread extends Thread {

@Override

public void run() {

// TODO Auto-generated method stub

super.run();

try {

while (clickdown) {

sleep(mtime);

mListener.onLongTouch(MButton.this.getId(),

(RobotButtonItem) getTag());

}

mListener.onUpTouch();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

public void setOnLongTouchListener(LongTouchListener listener, int time) {

mListener = listener;

mtime = time;

}

public LongTouchListener getLongTouchListener() {

return mListener;

}

/**

* 长按监听接口,使用按钮长按的地方应该注册此监听器来获取回调。

*/

public interface LongTouchListener {

void onLongTouch(int id, RobotButtonItem item);

void onUpTouch();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值