按钮长按,值按频率变化。
package com.coretech.defobject; import android.content.Context; import android.os.Handler; import android.util.AttributeSet; import android.view.MotionEvent; import android.widget.Button; public class LongPressButton extends Button { private int mLastMotionX, mLastMotionY; // 是否移动了 private boolean isMoved; // 是否释放了 private boolean isReleased; // 计数器,防止多次点击导致最后一次形成longpress的时间变短 private int mCounter; // 长按的runnable private Runnable mLongPressRunnable; // 移动的阈值 private static final int TOUCH_SLOP = 20; //激活的频率 private static final int PRESS_INTERVAL = 200; private final Handler mHandler = new Handler(); public LongPressButton(Context context) { super(context); } public LongPressButton(Context context, AttributeSet attr) { //必须重写,否则android.view.InflateException: Binary XML file line #165: Error inflating class super(context, attr); } private void createRunnable() { mLongPressRunnable = new Runnable() { @Override public void run() { mCounter--; // 计数器大于0,说明当前执行的Runnable不是最后一次down产生的。 if (mCounter > 0 || isReleased || isMoved) return; performLongClick(); mHandler.postDelayed(this, PRESS_INTERVAL); } }; mHandler.postDelayed(mLongPressRunnable, 10); } @Override public boolean dispatchTouchEvent(MotionEvent event) { int x = (int) event.getX(); int y = (int) event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mLastMotionX = x; mLastMotionY = y; mCounter++; isReleased = false; isMoved = false; // int iTime = ViewConfiguration.getLongPressTimeout(); createRunnable(); break; case MotionEvent.ACTION_MOVE: if (isMoved) break; if (Math.abs(mLastMotionX - x) > TOUCH_SLOP || Math.abs(mLastMotionY - y) > TOUCH_SLOP) { // 移动超过阈值,则表示移动了 isMoved = true; } break; case MotionEvent.ACTION_UP: // 释放了 isReleased = true; break; } return true; } }
引用
btn_weight_dec.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { tv_weight.setText("" + (Float.parseFloat(tv_weight.getText().toString()) - 0.1)); return false; } });
posted on 2014-04-18 14:38 strangeman 阅读(350) 评论(0) 编辑 收藏 举报