Android Clipboard Tutorial

Advertisements


Android provides the clipboard framework for copying and pasting different types of data. The data could be text , images, binary stream data or other complex data types.

Android provides the library of ClipboardManager and ClipData and ClipData.item to use the copying and pasting framework.In order to use clipboard framework, you need to put data into clip object, and then put that object into system wide clipboard.

In order to use clipboard , you need to instantiate an object of ClipboardManager by calling the getSystemService() method. Its syntax is given below:

ClipboardManager myClipboard;
myClipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);

Copying data

The next thing you need to do is to instantiate the ClipData object by calling the respective type of data method of the ClipData class. In case of text data , the newPlainText method will be called. After that you have to set that data as the clip of the Clipbaoard Manager object.Its syntax is given below:

ClipData myClip;
String text = "hello world";
myClip = ClipData.newPlainText("text", text);
myClipboard.setPrimaryClip(myClip);

The ClipData object can take these three form and following functions are used to create those forms.

Sr.NoClipData Form & Method
1Text
newPlainText(label, text)
Returns a ClipData object whose single ClipData.Item object contains a text string.
2URI
newUri(resolver, label, URI)
Returns a ClipData object whose single ClipData.Item object contains a URI.
3Intent
newIntent(label, intent)
Returns a ClipData object whose single ClipData.Item object contains an Intent.

Pasting data

In order to paste the data, we will first get the clip by calling the getPrimaryClip() method. And from that click we will get the item in ClipData.Item object. And from the object we will get the data. Its syntax is given below:

ClipData abc = myClipboard.getPrimaryClip();
ClipData.Item item = abc.getItemAt(0);
String text = item.getText().toString();

Apart from the these methods , there are other methods provided by the ClipboardManager class for managing clipboard framework. These methods are listed below:

Sr.NoMethod & description
1getPrimaryClip()
This method just returns the current primary clip on the clipboard
2getPrimaryClipDescription()
This method returns a description of the current primary clip on the clipboard but not a copy of its data.
3hasPrimaryClip()
This method returns true if there is currently a primary clip on the clipboard
4setPrimaryClip(ClipData clip)
This method sets the current primary clip on the clipboard
5setText(CharSequence text)
This method can be directly used to copy text into the clipboard
6getText()
This method can be directly used to get the copied text from the clipboard

Example

Here is an example demonstrating the use of ClipboardManager class. It creates a basic copy paste application that allows you to copy the text and then paste it via clipboard.

To experiment with this example , you can run this on an actual device or in an emulator.

StepsDescription
1You will use Eclipse IDE to create an Android application and name it as Clipboard under a package com.example.clipboard. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Modify src/MainActivity.java file to add necessary code.
3Modify the res/layout/activity_main to add respective XML components
4Modify the res/values/string.xml to add necessary string components
5Run the application and choose a running android device and install the application on it and verify the results

Following is the content of the modifed main activity file src/com.example.clipboard/MainActivity.java.

package com.example.clipboard;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

   private ClipboardManager myClipboard;
   private ClipData myClip;
   private EditText copyField,pasteField;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      myClipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
      copyField = (EditText)findViewById(R.id.editText1);
      pasteField = (EditText)findViewById(R.id.editText2);

   }

   @SuppressLint("NewApi")
   public void copy(View view){
      String text = copyField.getText().toString();
      myClip = ClipData.newPlainText("text", text);
      myClipboard.setPrimaryClip(myClip);
      Toast.makeText(getApplicationContext(), "Text Copied", 
      Toast.LENGTH_SHORT).show();
   }

   @SuppressLint("NewApi")
   public void paste(View view){
      ClipData abc = myClipboard.getPrimaryClip();
      ClipData.Item item = abc.getItemAt(0);
      String text = item.getText().toString();
      pasteField.setText(text);
      Toast.makeText(getApplicationContext(), "Text Pasted", 
      Toast.LENGTH_SHORT).show();
   }

   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
   }

}

Following is the modified content of the xml res/layout/activity_main.xml.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context=".MainActivity" >

   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentLeft="true"
      android:layout_alignParentTop="true"
      android:layout_marginLeft="25dp"
      android:layout_marginTop="19dp"
      android:text="@string/copytext"
      android:textAppearance="?android:attr/textAppearanceLarge" />

   <EditText
      android:id="@+id/editText1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignLeft="@+id/textView1"
      android:layout_below="@+id/textView1"
      android:layout_marginTop="20dp"
      android:ems="10" >

      <requestFocus />
   </EditText>

   <TextView
      android:id="@+id/textView2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignLeft="@+id/editText1"
      android:layout_centerVertical="true"
      android:text="@string/pastetext"
      android:textAppearance="?android:attr/textAppearanceLarge" />

   <Button
      android:id="@+id/button1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignLeft="@+id/editText1"
      android:layout_below="@+id/editText1"
      android:layout_marginLeft="65dp"
      android:layout_marginTop="20dp"
      android:onClick="copy"
      android:text="@string/copy" />

   <EditText
      android:id="@+id/editText2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignLeft="@+id/textView2"
      android:layout_below="@+id/textView2"
      android:layout_marginTop="39dp"
      android:ems="10" />

   <Button
      android:id="@+id/button2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignLeft="@+id/button1"
      android:layout_below="@+id/editText2"
      android:layout_marginTop="34dp"
      android:onClick="paste"
      android:text="@string/paste" />

</RelativeLayout>

Following is the content of the res/values/string.xml.

<?xml version="1.0" encoding="utf-8"?>
<resources>

   <string name="app_name">Clipboard</string>
   <string name="action_settings">Settings</string>
   <string name="hello_world">Hello world!</string>
   <string name="copy">Copy Text</string>
   <string name="paste">Paste Text</string>
   <string name="copytext">Text to copy</string>
   <string name="pastetext">Copied Text</string>
</resources>

Following is the content of AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.clipboard"
   android:versionCode="1"
   android:versionName="1.0" >

   <uses-sdk
      android:minSdkVersion="8"
      android:targetSdkVersion="17" />

   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      <activity
         android:name="com.example.clipboard.MainActivity"
         android:label="@string/app_name" >
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>

</manifest>

Let's try to run our Clipboard application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Eclipse installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window:

Anroid clipboard Tutorial

Now just enter any text in the Text to copy field and then select the copy text button. The following notification will be displayed which is shown below:

Anroid clipboard Tutorial

Now just press the paste button, and you will see the text which is copied is now pasted in the field of Copied Text. It is shown below:

Anroid clipboard Tutorial

Advertisements
Advertisements