Home > front end >  Listeners inside detectTapGestures only ever get the first variable value - Other Compose views upda
Listeners inside detectTapGestures only ever get the first variable value - Other Compose views upda

Time:01-26

I am trying to copy a text passed into a Compose view on long press. It is not directly the value, but instead, it's something like itemText ?: "Fallback". The thing is, the value of the parameter text inside the onLongPress lambda is never updated. Only the first value gets taken. This was both evaluated debugging & using toasts to display the value.

Also tried out many other things, including not using remember, using a function instead of directly using itemText ?: "Fallback", etc.

Inside the Button's onClickListener, the value is always up to date.

Am I doing something wrong or is there a Compose bug in there somewhere? As I am guessing that it's a bug, I have reported it to the issue tracker: https://issuetracker.google.com/issues/216160969

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            ComposeTutoriaTheme {
                Sample()
            }
        }
    }
}

@Composable
fun Sample() {
    var itemText: String? by remember {
        mutableStateOf(null)
    }

    Column {
        Button(
            modifier = Modifier.padding(top = 10.dp, bottom = 20.dp),
            onClick = {
                itemText = if (itemText == null) {
                    "Tomato"
                } else {
                    null
                }
            }
        ) {
            Text(text = "Tap to toggle")
        }

        GroceryItem(text = itemText ?: "Fallback")
    }
}

@Composable
fun GroceryItem(text: String) {
    val context = LocalContext.current
    Text(
        modifier = Modifier.pointerInput(Unit) {
            detectTapGestures(
                onLongPress = {
                    Toast.makeText(context, text, Toast.LENGTH_LONG).show()
                }
            )
        },
        text = text
    )

    Button(
        onClick = {
            Toast.makeText(context, text, Toast.LENGTH_LONG).show()
        }
    ) {
        Text(text = "Button to copy from, onClick")
    }
}

CodePudding user response:

This is expected behavior.

Modifier.pointerInput remembers all variables, just like remember does. This is done so as not to interrupt touch handling during any recomposition.

And same as with remember, you can pass any parameters you need to keep track of as a key parameter instead of Unit:

Modifier.pointerInput(text) {
    detectTapGestures(
        onLongPress = {
            Toast.makeText(context, text, Toast.LENGTH_LONG).show()
        }
    )
},
  •  Tags:  
  • Related