Search code examples
javaandroidkotlinonclicklistenerontouchlistener

How to add onClickListener for a button after keep clicking on it for a while?


Hi guys i'm a beginner android dev and i have a question that i didn't find it answer yet. I want to add an onClickListener for a Button after keep clicking on it for 1.5 seconds for example?


Solution

  • Originally Answered

    You can't define custom duration for onLongClickListener() Rather you should use onTouchListener and see the time when the user clicked on the button and when that time surpassed your limit do your code like this

    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;
            }
        });