Android Text Selection on TextView And EditText Tutorial

This tutorial explains how to implement custom text selection behavior means how to copy and paste of selected text in Android Application.

 



Introduction

Android Marshmallow  provides a new way to handle selected text in any Android application. To select text in Android application, long hold on a word then a blue color appear to adjust your text selection (we can drag them word by word) . Now a toolbar at the top with obscure icons representing cutting, copying and pasting. You can also paste copied text on any other application.

 

In this tutorial, we will learn how to implement Text Selection in Android application. We would have to long hold on word to select text, when you hold on word then a toolbar appear at the top with option copy, cut and paste. We need to choose any of the one option to be perform operation. We can also paste copied text in any other application. For that, only we need to intent-filter in the <activity> section in AndroidManifest.xml file.

 

Add Intent Filter

To enable Text Selection behavior in Android Application, we need to add intent filter in the <activity> section in AndroidManifest.xml file. Manifest file look like this:

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

    <application>
          ......
            <intent-filter >
                <action android:name="android.intent.action.PROCESS_TEXT"/>
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="text/plain" />
            </intent-filter>
        </activity>
    </application>

</manifest>

 
 

Create Layout

To select text, we need to add bufferType=”spannable” and textIsSelectable=”true” in TextView.

<TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:bufferType="spannable"
        android:textIsSelectable="true"
        android:text="Long hold to select text and we can copy it and paste in any other application" />

 
 

textSelection

  
 
  



The following two tabs change content below.
Abhay Anand has experience in the field of Software Development. He can program Android, PHP, JavaScript, Html, Css. He develops web and Android applications. You can reach him at anand.abhay1910@gmail.com
  • Raj Sinha

    Thanks, it helped me