0

I am trying to implement situtation in android where if user presses button for 5 seconds, then it should perform some action.

Generally, user presses specific button for 5+ seconds, and then listener should be triggered after this.

I would appreciate your answer.

Khamidjon Khamidov
  • 6,783
  • 6
  • 31
  • 62

1 Answers1

0

I have found solution for this problem

private var job: Job? = null
private var iSBeingClicked = false

fun initBtn() {
btnPlusMinus.setOnTouchListener { view, event ->
            if(event.action == MotionEvent.ACTION_DOWN) {
                isBeingClicked = true
                job?.cancel()
                job = lifecycleScope.launch {
                    delay(5000)
                    if(isBeingClicked) {
                        // do whatever your action
                        isBeingClicked = false
                    }
                }
            }

            if((event.action == MotionEvent.ACTION_UP)) {
                isBeingClicked = false
                job?.cancel()
                // if btn pressed out in less than 5 secs
                // it should perform traditional click 
                btnPlusMinus.performClick()
            }

            true
        }
}
Khamidjon Khamidov
  • 6,783
  • 6
  • 31
  • 62