Cut, copy, paste in android

两盒软妹~` 提交于 2019-11-27 02:52:32

问题


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


来源:https://stackoverflow.com/questions/6185676/cut-copy-paste-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!