Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable copy/paste/cut in a TextField Jetpack Compose?

I'm trying to find a simple solution on how to disable copy/paste/cut in a TextField. I did come across a couple of question but no answer.

like image 406
Limun Avatar asked Nov 29 '25 21:11

Limun


2 Answers

Create an empty toolbar:

object EmptyTextToolbar: TextToolbar {
    override val status: TextToolbarStatus = TextToolbarStatus.Hidden

    override fun hide() {  }

    override fun showMenu(
        rect: Rect,
        onCopyRequested: (() -> Unit)?,
        onPasteRequested: (() -> Unit)?,
        onCutRequested: (() -> Unit)?,
        onSelectAllRequested: (() -> Unit)?,
    ) {
    }
}

Then you can provide it using LocalTextToolbar.

Most probably you also don't need text selection in this case, here's how you can disable it too:

var textValue by remember { mutableStateOf(TextFieldValue("")) }
CompositionLocalProvider(
    LocalTextToolbar provides EmptyTextToolbar
) {
    TextField(
        value = textValue,
        onValueChange = { newValue ->
            textValue = if (newValue.selection.length > 0) {
                newValue.copy(selection = textValue.selection)
            } else {
                newValue
            }
        }
    )
}
like image 187
Philip Dukhov Avatar answered Dec 02 '25 05:12

Philip Dukhov


For now, you could just add a dummy Transparent Composable on TOP of the TextField and hook up it's click listener with the TextField's focusRequestor.

val tffr = remember { FocusRequestor() } // TextField Focus-Requestor

Box{

 TextField(
   value = value,
   onValueChange = { value = it }
   modifier = Modifier.focusRequestor(tffr).focusable()
 )

 Surface(
  modifier = Modifier.clickable { tffr.requestFocus() }.alpha(0)
 )

}

This way, when users try to click on the TextField, the tap would be intercepted by our dummy Composable, which would transfer the focus, effectively, to the TextField.

This means that they will technically be allowed to tap on the TextField and type in it, but the long press won't be registered by the field for them.

You could even add a Long-Click-Listener to the Surface using the combinedClick modifier, and display a toast to they users stating that the copy/paste actions are disabled, if that is something you'd require, that is.

like image 24
MARSK Avatar answered Dec 02 '25 03:12

MARSK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!