Home > OS >  Detect when the user stops pressing the button Jetpack Compose
Detect when the user stops pressing the button Jetpack Compose

Time:12-15

I have a button and I want it to execute an action only while it is long pressed.

I am able to execute the action on the long press already, the problem is I do not know how to stop it once the user is no longer pressing down on the button.

1)How would one go about implementing something like this?

I am using Jetpack Compose on an Android App

CodePudding user response:

This code is not tested yet. But I believe this is what you are looking for:

Button(
  onClick = { /* TODO */ },
  modifier = Modifier.pointerInteropFilter {
    when(it.action) {
      MotionEvent.ACTION_DOWN -> {
        // User has pressed the button
      }
      MotionEvent.ACTION_UP -> {
        // User is no longer pressing the button
      }
      else -> false
    }
    true
  }
) {
  Text(text = "Click Me")
}

Don't forget about @ExperimentalPointerInput annotation.

CodePudding user response:

The Gestures API is probably what you are after.

You can use something like:

var longPressActive by remember { mutableStateOf(false) }

Modifier.pointerInput(Unit) {
  detectTapGestures(
    onLongPress = { longPressActive = true }
    onPress = {
      awaitRelease()
      longPressActive = false
    }
  )
}

You may also find other APIs regarding drag that match your requirements. May be worth expanding on what you are ultimately trying to accomplish.

CodePudding user response:

To do this, the Button has an argument interactionSource. It can be used as follows:

val interactionSource = remember { MutableInteractionSource() }
val isPressed by interactionSource.collectIsPressedAsState()

Button(
    onClick = { /*TODO*/ }
    interactionSource = interactionSource,
) {

}

If you need to perform some action until the button is released, you can use isPressed with LaunchedEffect:

if (isPressed) {
    LaunchedEffect(Unit) {
        // execute some action
    }
}

It is launched in a coroutine scope, which will be canceled as soon as isPressed becomes false.

An other option is using it with DisposableEffect:

if (isPressed) {
    DisposableEffect(Unit) {
        // do some action
        onDispose {
            // cancel some action
        }
    }
}
  • Related