Cut, copy, paste in android

2020-02-05 04:22发布

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 !!

3条回答
欢心
2楼-- · 2020-02-05 04:49

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楼-- · 2020-02-05 05:01

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);
查看更多
forever°为你锁心
4楼-- · 2020-02-05 05:03

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.

查看更多
登录 后发表回答