Android TextView Copy Paste Using Clipboard

Filed Under: Android

In this tutorial, we’ll implement the copy-paste feature on a TextView in our Android Application.
At the end of this article, you’d be able to copy a text to the Android System’s Clipboard and then paste that Clipboard data.

Andorid Clipboard – Copy Paste

You must have noticed that EditText has a built in Clipboard Manager for Copy Paste functionality.
But a TextView doesn’t. So in order to allow Copy Pasting TextViews, we need to register the ContextMenu.

Hence in order to receive the menu events, we need to registerForContextMenu.
Once this is done, you can long-press on the TextView to display the menu.

But where’s the menu?

The menu is created in the onCreateContextMenu() method.
The menu items actions are set in the onContextItemSelected method.

Copying Text To Clipboard

It’s easy to copy TextView text onto the Clipboard. You just need to set the ClipData type as newPlainText and pass the string.

Example:


ClipboardManager manager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); 
ClipData clipData = ClipData.newPlainText("text", textView.getText());
manager.setPrimaryClip(clipData);

Pasting Text To Clipboard

Now that you have copied the text onto the Clipboard, just paste it using the following piece of code:


ClipData pasteData = manager.getPrimaryClip();
ClipData.Item item = pasteData.getItemAt(0);
String paste = item.getText().toString();

Here we’re pasting the first data from the Clipboard. If we have multiple copied texts, they can be pasted using pasteData.getItemAt(1) and so on.

Now let’s jump onto the implementation part of this article.
In the next section, we’ll be developing a simple Android Application in which you can copy-paste text from one TextView to another.

Project Structure

Android Textview Copy Paste Project Structure

Android Textview Copy Paste Project Structure

Code

The code for the activity_main.xml layout is given below:


<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tvCopy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Welcome To Journaldev.com"
        android:padding="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />


    <TextView
        android:id="@+id/tvPaste"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Paste here"
        android:padding="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvCopy" />

</androidx.constraintlayout.widget.ConstraintLayout>

The code for the MainActivity.java class is given below:


package com.journaldev.androidtextviewcopypaste;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


    TextView tvCopy, tvPaste;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvCopy = findViewById(R.id.tvCopy);
        tvPaste = findViewById(R.id.tvPaste);

        registerForContextMenu(tvCopy);
        registerForContextMenu(tvPaste);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);

        menu.setHeaderTitle("Options");
        switch (v.getId()) {
            case R.id.tvCopy:
                menu.add(0, v.getId(), 0, "Copy");
                TextView textView = (TextView) v;
                ClipboardManager manager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                ClipData clipData = ClipData.newPlainText("text", textView.getText());
                if (manager != null) {
                    manager.setPrimaryClip(clipData);
                }

                break;
            case R.id.tvPaste:
                menu.add(0, v.getId(), 0, "Paste");
                break;
        }
    }

    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {

        switch (item.getItemId()) {
            case R.id.tvCopy:
                Toast.makeText(getApplicationContext(), "Copy Clicked", Toast.LENGTH_LONG).show();
                break;
            case R.id.tvPaste:
                ClipboardManager manager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                if (manager != null && manager.getPrimaryClip() != null && manager.getPrimaryClip().getItemCount() > 0) {
                    tvPaste.setText(manager.getPrimaryClip().getItemAt(0).getText().toString());
                }

                break;
        }


        return super.onContextItemSelected(item);


    }
}

getItemCount() is used to get the items present in the clipboard.
You can also set the clipboard data to be copied in the onContextItemSelected copy menu item action.

Output

The output of the above application in action is given below:

Android Textview Copy Paste Output

Android Textview Copy Paste Output

That sums up this tutorial. Can you add a Cut Menu option? Post your code snippets in the comment sections!

Download Links

You can do ahead and download the full source code from the link below or visit our Github Repository.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages