继续单击一段时间后如何为按钮添加onClickListener?

时间:2021-04-14 15:49:11

标签: java android kotlin onclicklistener ontouchlistener

大家好,我是 android 开发初学者,我有一个问题,我还没有找到答案。例如,我想在持续点击按钮 1.5 秒后为按钮添加一个 onClickListener?

1 个答案:

答案 0 :(得分:0)

Originally Answered

您无法为 onLongClickListener() 定义自定义持续时间 相反,您应该使用 onTouchListener 并查看用户单击按钮的时间 当那个时间超过你的限制时,你的代码是这样的

Button your_button = findViewById(R.id.your_button_ID);
long time = 0;
    button.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if(event.getAction() == MotionEvent.ACTION_DOWN){
                time = (Long) System.currentTimeMillis();
            }
            else if(event.getAction() == MotionEvent.ACTION_UP){
                if(((Long) System.currentTimeMillis() - time) > 1500){
 // if time>1.5 seconds do your code here

                    return true;
                }
            }
            return false;
        }
    });