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:
Copy Code
<?xmlversion="1.0"encoding="utf-8"?><RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"><TextViewandroid: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:
Copy Code
importandroid.os.Bundleimportandroid.view.ActionModeimportandroid.view.Menuimportandroid.view.MenuItemimportandroid.widget.TextViewimportandroid.widget.Toastimportandroid.content.ClipDataimportandroid.content.ClipboardManagerimportandroidx.appcompat.app.AppCompatActivityclassMainActivity: AppCompatActivity() {private lateinit vartextView: TextViewoverride 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 selectiontextView.setOnLongClickListener {
startActionMode(actionModeCallback)true
}
}
private valactionModeCallback = object : ActionMode.Callback {
override funonCreateActionMode(mode: ActionMode?, menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_copy, menu)return true
}
override funonPrepareActionMode(mode: ActionMode?, menu: Menu?): Boolean {
// Return false if nothing is donereturn false
}
override funonActionItemClicked(mode: ActionMode?, item: MenuItem?): Boolean {
return when (item?.itemId) {R.id.menu_copy -> {
copyText()mode?.finish()// Close the CABtrue
}
else -> false
}
}
override funonDestroyActionMode(mode: ActionMode?) {
// No implementation needed
}
}
private funcopyText() {
// Get text from TextView and copy to clipboardval clipboardManager = getSystemService(CLIPBOARD_SERVICE) as ClipboardManagerval clipData = ClipData.newPlainText("Copied Text", textView.text)
clipboardManager.setPrimaryClip(clipData)// Show toast or feedback indicating text copiedToast.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:
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.