Site icon PCSalt

Copy to Clipboard Programmatically – Android

Clipboard is a type of register where copied contents are kept by Android. If you require to keep some text content which could be used for later use, you can have it in Clipboard. But, don’t rely on clipboard for storing it permanently. For temporary use it is a nice place to have content.

Clipboard stores contents of last copy. But, some android devices are providing option to paste from last 10 copies.

In this demo application ClipboardManager we are going to add content of EditText to Clipboard on a Button click.

Create an Android Application Project with following values:

  1. Prepare layout screen
    activity_main.xml
        
        
  2. Initialize activity
    MainActivity.java
    package pcsalt.example.clipboardmanager;
    import android.annotation.SuppressLint;
    import android.app.Activity;
    import android.content.ClipData;
    import android.content.Context;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    public class MainActivity extends Activity {
    	EditText etMessage;
    	Button btnCopy;
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    		etMessage	= (EditText) findViewById(R.id.etMessage);
    		btnCopy 	= (Button)	 findViewById(R.id.btnCopy);
    		// on button click copy text in EditText to clipboard
    		btnCopy.setOnClickListener(new OnClickListener() {
    			@SuppressWarnings("deprecation")
    			@SuppressLint("NewApi")
    			@Override
    			public void onClick(View arg0) {
    				String text = etMessage.getText().toString().trim();
    				if(text.length() > 0) {
    					if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
    						android.text.ClipboardManager clipboardMgr = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    						clipboardMgr.setText(text);
    					} else {
    						// this api requires SDK version 11 and above, so suppress warning for now
    						android.content.ClipboardManager clipboardMgr = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    						ClipData clip = ClipData.newPlainText("Copied text", text);
    						clipboardMgr.setPrimaryClip(clip);
    					}
    				}
    			}
    		});
    	}
    }
    

Here, a comparison is made to detect if the device is having Honeycomb or above or not. It is done because, for Honeycomb and above a new API class android.content.ClipboardManager is available. For previous version there is android.text.ClipboardManager class available.

Download source:

Video tutorial:

Exit mobile version