我想要两个单独的事件用于长按向下和长按向上。我怎么能在Android中做到这一点?

我试过如下

public class FfwRewButton extends ImageButton {

    public interface ButtonListener {

        void OnLongClickDown(View v);

        void OnLongClickUp(View v);
    }

    private ButtonListener mListener;

    private boolean mLongClicked = false;

    public FfwRewButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setFocusable(true);
        setLongClickable(true);
    }

    public FfwRewButton(Context context) {
        this(context, null);
    }

    public FfwRewButton(Context context, AttributeSet attrs) {
        this(context, attrs, android.R.attr.imageButtonStyle);
    }

    @Override
    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
        Log.d("my listener", "long press");
        mLongClicked = true;
        mListener.OnLongClickDown(this);
        return super.onKeyLongPress(keyCode, event);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.d("my listener", "key down");
        mLongClicked = false;
        if (true) {
            super.onKeyDown(keyCode, event);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        Log.d("my listener", "key up");
        if (mLongClicked)
            mListener.OnLongClickUp(this);
        return super.onKeyUp(keyCode, event);
    }

    public void setFfwRewButtonListener(ButtonListener listener) {
        mListener = listener;
    }
}

在一项 Activity 中,我这样称呼它
private FfwRewButton.ButtonListener mListener = new FfwRewButton.ButtonListener() {

        @Override
        public void OnLongClickUp(View v) {
            Log.d(TAG, "longClickup");
        }

        @Override
        public void OnLongClickDown(View v) {
            Log.d(TAG, "longClickdown");
        }
    };

但仍然没有在 logcat 中收到任何日志消息
谁能帮我;我错在哪里?

最佳答案

onKeyXXX() 方法用于来自键盘或硬键(如菜单键、搜索键等)的键事件。

如果要检测触摸事件,Android 中称为 MotionEvent,则必须覆盖 onTouchEvent(MotionEvent e) 方法并使用 GestureDetector 类来识别长按。

private GestureDetector mGestureDetector;

public FfwRewButton(...) {
    //....
    mGestureDetector = new GestureDetector(context,
        new GestureDetector.SimpleOnGestureListener() {
            public boolean onDown(MotionEvent e) {
                mLongClicked = false;
                return true;
            }
            public void onLongPress(MotionEvent e) {
                mLongClicked = true;
                // long press down detected
            }
        });
    }

    public boolean onTouchEvent(MotionEvent e) {
        mGestureDetector.onTouchEvent(e);
        if (mLongClicked && e.getAction() == ACTION_UP) {
           // long press up detected
        }
    }
}

关于android - Android 中长按和长按的事件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14877009/

10-10 23:31