android-widgetandroid-edittextandroidandroid-keypad

How to disable copy/paste from/to EditText


In my application, there is a registration screen, where i do not want the user to be able to copy/paste text into the EditText field. I have set an onLongClickListener on each EditText so that the context menu showing copy/paste/inputmethod and other options does not show up. So the user won't be able to copy/ paste into the Edit fields.

 OnLongClickListener mOnLongClickListener = new OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            // prevent context menu from being popped up, so that user
            // cannot copy/paste from/into any EditText fields.
            return true;
        }
    };

But the problem arises if the user has enabled a third-party keyboard other than the Android default, which may have a button to copy/paste or which may show the same context menu. So how do i disable copy/paste in that scenario ?

Please let me know if there are other ways to copy/paste as well. (and possibly how to disable them)

Any help would be appreciated.


Solution

  • If you are using API level 11 or above then you can stop copy,paste,cut and custom context menus from appearing by.

    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;
                }
            });
    

    Returning false from onCreateActionMode(ActionMode, Menu) will prevent the action mode from being started(Select All, Cut, Copy and Paste actions).