Cut, copy, paste in android

2020-02-05 04:10发布

问题:

I want to implement the cut,copy, paste functionality in my EditText,i tried with the following code :

    ClipMan = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    editbox1.setText(ClipMan.getText());

for paste the text,but it paste the whole text in another Editbox..I want to copy the selected text and paste that text in the same Editbox just like the normal notepad works..

Any suggestions are greatly appreciated... Thanks !!

回答1:

for copy data

ClipData clip = ClipData.newPlainText("simple text",Value);
ClipMan.setPrimaryClip(clip);

and get data which was copied

CharSequence pasteData="";
ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);
pasteData = item.getText();

in your case you can use EditText.getText() instead of Value.. and EditText.setText(pasteData); for paste that data.



回答2:

Finally i am able to copy ,paste in my application..now i can paste only selected text by using this code :

Editable s1;
EditText editbox2;

to copy the selected text :

       if(editbox2.getSelectionEnd() > editbox2.getSelectionStart()) 
        {
            s1 = (Editable) editbox2.getText().subSequence(editbox2.getSelectionStart(), editbox2.getSelectionEnd());
        }else
        {
            s1 = (Editable) editbox2.getText().subSequence(editbox2.getSelectionEnd(), editbox2.getSelectionStart());
        }

to paste the selected text:

             editbox2.getText().replace(Math.min(editbox2.getSelectionStart(),editbox2.getSelectionEnd()), Math.max(editbox2.getSelectionStart(), editbox2.getSelectionEnd()),s1, 0, s1.length());


回答3:

we can do this way :

    int min2 = 0;
    int max2 = editText.getText().length();
    if (editText.isFocused()) {
        final int selStart = editText.getSelectionStart();
        final int selEnd = editText.getSelectionEnd();

        min2 = Math.max(0, Math.min(selStart, selEnd));
        max2 = Math.max(0, Math.max(selStart, selEnd));
     }
     ClipData abc = myClipboard.getPrimaryClip();
     ClipData.Item item = abc.getItemAt(0);

     String text = item.getText().toString();
     editText.getText().replace(min2,max2 , text);