Search code examples
javaandroidandroid-edittextcopy-paste

How to remove text formatting when pasting from clipboard on Android


Right now I am working on an Android application that requires allowing the user to cut copy and paste onto an editText fields. But when I copy a formatted string from other places (i.e. a string that is underlined) and paste it on to the editText field, it shows it as a formatted version. How do I remove this?

I have tried to add a textwatcher by adding addTextChangedListener, and in the after text change I just do edittext.setText(s.toString()+"") but this creates an infinite loop. :(

Please help! Thanks in advance.

Edit---- I have made some progress by setting setCustomSelectionActionModeCallback

editDestination_.setCustomSelectionActionModeCallback(new Callback() {
        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {return true;}
        @Override
        public void onDestroyActionMode(ActionMode mode) {}
        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
             menu.removeItem(android.R.id.paste);
             menu.removeItem(android.R.id.selectAll);
             menu.add(0, CUSTOM_PASTE, 0, "Paste").setIcon(R.drawable.paste_ic);
                return true;
        }
        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
             switch (item.getItemId()) {
                case CUSTOM_PASTE:
                       edittext.setText(readFromClipboard(aContext_));
                    // Finish and close the ActionMode
                    mode.finish();
                    return true;
                default:
                    break;
            }
            return false;
        }
    });

This is working pretty well until I realize there are two types of cut/copy/and paste on my phone. One is when the edit text is empty and I long click on the field. This bring up a popup menu. The other one is when there is text in the field, and when I long click, this bring up a cut/copy/and paste bar below my action bar. My code from above is only affecting the bar-below-action bar one. :(


Solution

  • I have solved it.

    I set a onLongClickListener to catch it before the popup-cut/copy/paste menu shows up.

    CharSequence actions[] = new CharSequence[] {"paste"};
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setCancelable(true);
    builder.setItems(actions, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            edittext.setText(readFromClipboard(aContext_));
        }
    });
    builder.show();
    

    Then if there is a string already present in the EditText, I return false to allow normal android system below-action-bar-cut/copy/paste function to work.