Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get button pressed time when I holding button on

I have a button, I press it and continue to holding it, if holding time exceeds certain time interval it fires some kind of intent, how can i do this. Thanks

like image 705
RealDream Avatar asked Mar 24 '14 10:03

RealDream


3 Answers

long lastDown;
long keyPressedDuration ;

button.setOnTouchListener(new OnTouchListener() {
     @Override
     public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN) {
           lastDown = System.currentTimeMillis();
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
           keyPressedDuration = System.currentTimeMillis() - lastDown;
        }
     }
  };
like image 129
Kanaiya Katarmal Avatar answered Oct 26 '22 06:10

Kanaiya Katarmal


try this

You can use Touch Listener to do this.

Try:

Handler handler = new Handler();
    b.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View arg0, MotionEvent arg1) {
            switch (arg1.getAction()) {
            case MotionEvent.ACTION_DOWN:
                handler.postDelayed(run, 5000/* OR the amount of time you want */);
                break;

            default:
                handler.removeCallbacks(run);
                break;

            }
            return true;
        }
    });

Where b is the view (in your case it should button) on which you want to make long click.

And Runnable run is as follows

Runnable run = new Runnable() {

    @Override
    public void run() {
        // Your code to run on long click

    }
};

Hope it will help... :)

like image 28
Hardik Avatar answered Oct 26 '22 06:10

Hardik


Detect [ACTION_DOWN][1] and [ACTION_UP][2] events.

When button is pressed ([ACTION_DOWN][1]), start timer, measure time... If timer exceeds, invoke Intent. When button is released ([ACTION_UP][2]) stop timer.

final Timer timer = new Timer();
button.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View arg0, MotionEvent arg1) {
        switch ( arg1.getAction() ) {
        case MotionEvent.ACTION_DOWN:
            //start timer
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    // invoke intent
                }
            }, 5000); //time out 5s
            return true;
        case MotionEvent.ACTION_UP:
            //stop timer
            timer.cancel();
            return true;
        }
        return false;
    }
});

When button will be pressed, timer will be started. If button will be released before 5 seconds timeout, nothing will happen, otherwise your desired action will be executed.

like image 7
Dario Avatar answered Oct 26 '22 06:10

Dario