2014년 6월 26일 목요일

How to Copy & Paste in Android (Clipboard)

When we run applications like Google Drive, Gmail, or any text editing apps, it's easy to copy and paste something. it's possible to grab an image from browser and paste it in memo app as well.

how does this work?
If you go through Android Developers site, you can find ClipBoard Framework.
Basically Android provides ClipBoard Framework for specifially Copy & Paste.
The following digram (taken from Android Developers site) shows flow and how this works.




Google provides basic fundamental framework and I believe manufacturers like LG, Samsung did some customization this framework, for example on my LG phone, custom UI appears when copying some images & texts on browser (allowing max. 10 items to be stored in clipboard)
 
Anyway it's really easy to use ClipBoard Framework
The text that's being copied to Clipboard here is CopyText, the selected & copied text from TextView or EditText. The code snippets is really simple and clear.

ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);

ClipData clip = ClipData.newPlainText("Clip",CopyText);
Toast.makeText(mContext, "Copied to Clipboard", Toast.LENGTH_SHORT).show();
clipboard.setPrimaryClip(clip);


In order to paste, firstly check if  there exist a clip then get Item from clip. That's all.
I'm ready to paste.. done.

ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);

if(clipboard.hasPrimaryClip()== true){
 ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);
 pasteText = item.getText().toString();
 pasteTxt.setText(pasteText);
}



댓글 없음:

댓글 쓰기