Copy Text from TextView on Long Press - Android Code

In this tutorial, you will learn how to implement the functionality to copy text from a `TextView` when it is long-pressed in an Android app. The tutorial will guide you through the process of setting up a contextual action mode that triggers when the `TextView` is long-pressed. Within this action mode, you'll enable the option for users to select and copy the text displayed in the `TextView`. This approach enhances user interaction by providing a convenient way to extract and copy textual content from within your app's UI.
Submitted on July 07, 2024

To enable copying text content from a ‘TextView’ when long-pressed in an Android app, you can follow these steps. We’ll implement a solution where a contextual action mode is triggered upon long-pressing the ‘TextView’, allowing the user to copy the text.

Step-by-Step Implementation

1. Update Layout (activity_main.xml)

Add a ‘TextView’ in your layout (‘activity_main.xml’) where you want to enable text copying:


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Long press to copy this text"
        android:textSize="18sp"
        android:padding="16dp"
        android:textColor="@android:color/black" />

</RelativeLayout>

      

2. Implement MainActivity (MainActivity.kt)

In your ‘MainActivity.kt’, implement the logic to handle long-press and copying text:


import android.os.Bundle
import android.view.ActionMode
import android.view.Menu
import android.view.MenuItem
import android.widget.TextView
import android.widget.Toast
import android.content.ClipData
import android.content.ClipboardManager
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    private lateinit var textView: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        textView = findViewById(R.id.textView)

        // Set long click listener to start action mode for text selection
        textView.setOnLongClickListener {
            startActionMode(actionModeCallback)
            true
        }
    }

    private val actionModeCallback = object : ActionMode.Callback {

        override fun onCreateActionMode(mode: ActionMode?, menu: Menu?): Boolean {
            menuInflater.inflate(R.menu.menu_copy, menu)
            return true
        }

        override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?): Boolean {
            // Return false if nothing is done
            return false
        }

        override fun onActionItemClicked(mode: ActionMode?, item: MenuItem?): Boolean {
            return when (item?.itemId) {
                R.id.menu_copy -> {
                    copyText()
                    mode?.finish() // Close the CAB
                    true
                }
                else -> false
            }
        }

        override fun onDestroyActionMode(mode: ActionMode?) {
            // No implementation needed
        }
    }

    private fun copyText() {
        // Get text from TextView and copy to clipboard
        val clipboardManager = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
        val clipData = ClipData.newPlainText("Copied Text", textView.text)
        clipboardManager.setPrimaryClip(clipData)

        // Show toast or feedback indicating text copied
        Toast.makeText(this, "Text copied to clipboard", Toast.LENGTH_SHORT).show()
    }
}

      

3. Create Menu Resource (menu_copy.xml)

Create a menu resource file (‘menu_copy.xml’) under res/menu/ directory to define the copy action:


<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/menu_copy"
        android:title="Copy"
        android:icon="@android:drawable/ic_menu_copy"
        android:showAsAction="ifRoom" />
</menu>

      

ActionMode and Clipboard Handling in Android - Explanation and Implementation

Explanation:

  • Layout (activity_main.xml):

    • Contains a TextView with some sample text.
  • MainActivity (MainActivity.kt):

    • Sets an OnLongClickListener on the TextView to start an ActionMode when long-pressed.
    • Implements an ActionMode.Callback (actionModeCallback) to handle the contextual action mode for copying text.
    • Defines a copyText() function to retrieve text from the TextView and copy it to the clipboard using ClipboardManager.
  • Menu (menu_copy.xml):

    • Defines a menu item for copying text.

Additional Notes:

  • ClipboardManager: This is used to manage the clipboard in Android and requires the android.permission.WRITE_EXTERNAL_STORAGE permission, which is granted automatically in the latest versions.

This implementation allows users to copy text from a TextView within your Android app using ActionMode and ClipboardManager. Adjustments can be made based on your specific application requirements and desired user experience.