Disable paste from clipboard suggestions on EditText

1.1k views Asked by At

To prevent an EditText from receiving content from the clipboard, I disable the long click and text selectable, plus cleared the action mode menu:

EditText editText = findViewById(R.id.et);
editText.setCustomSelectionActionModeCallback(new ActionMode.Callback() {

        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        public void onDestroyActionMode(ActionMode mode) {
        }

        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            return false;
        }
    });
    editText.setTextIsSelectable(false);
    editText.setLongClickable(false);

The problem is that I keep receiving clipboard suggestions that when selected are pasted to my EditText. How can I disable this or simply ignore this pasted content?

1

There are 1 answers

0
Ahmed Nezhi On

To disable all types of copy past from keyboard, keyboard extension, Action Menu and any other type you can add a textChangeListener to your EditText and check in the method beforeTextChanged like the follow:

editText.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {}

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            if (after - count > 1) {
                editText.setText(s)
                editText.setSelection(s.toString().length)
            }
        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int){}

    })

this solution works if someone past more than one character at the time. Good luck