I'm trying to block the paste option in a TextInputEditText in Samsung

41 views Asked by At

I have a somewhat peculiar issue; I'm trying to block the paste option in a TextInputEditText. In fact, this works perfectly on my Pixel and other devices, but for some reason, it doesn't work for Samsung and Huawei devices. This is the code I've used:

fun onRestrictCopyAndPaste(inputText: TextInputEditText, textInputLayout: TextInputLayout){
        inputText.setOnLongClickListener { true }

        inputText.customSelectionActionModeCallback = object : ActionMode.Callback {
            override fun onCreateActionMode(mode: ActionMode?, menu: Menu?): Boolean {
                menu?.removeItem(android.R.id.paste)
                return false
            }
            override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?): Boolean {
                menu?.removeItem(android.R.id.paste)
                return false
            }
            override fun onActionItemClicked(mode: ActionMode?, item: MenuItem?): Boolean {

                return false
            }
            override fun onDestroyActionMode(mode: ActionMode?) {}
        }
    }

I've tried multiple options, including filters or attempting to block double-clicking, but nothing worked for Samsung or Huawei devices. I'm unsure if they manage the menu that appears at the top differently.

It appears on the screen like this

enter image description here

1

There are 1 answers

2
duhspbr On

There are still a few properties that need to be disabled to enhance security and user experience in Android:

fun EditText.disablePasteAndCopy() {
isLongClickable = false // Prevents long-press to display copy/paste options
setTextIsSelectable(false) // Disables text selection
this.customSelectionActionModeCallback = object : android.view.ActionMode.Callback {
    override fun onActionItemClicked(mode: android.view.ActionMode?, item: MenuItem?) = false
    override fun onCreateActionMode(mode: android.view.ActionMode?, menu: Menu?) = false // Initially set to true, changing to false prevents the action mode from being created
    override fun onPrepareActionMode(mode: android.view.ActionMode?, menu: Menu?): Boolean {
        menu?.clear() // Clears any existing options in the menu, effectively disabling copy and paste
        return false
    }

    override fun onDestroyActionMode(mode: android.view.ActionMode?) = Unit
}

}

Maybe the above snippet should help.