Selectable read-only multiline text field on Android

While working on the Android mobile application I faced a business requirement to let user copy a part of data from a long text field without letting him modifying the content.

Here is what I was to achieve

And here is what I had using an EditText

Thus there was a set of changes to be done:

  1. Remove Cut and Paste items from a menu which gets displayed when a user selects some text;
  2. Hide a menu which is displayed when a user taps on a cursor;
  3. Block keyboard appearing when a user taps on an EditText;
  4. Make EditText look more like a TextView.

So let’s make it step by step!

  1. To customize the menu which appears when a user selects some text, I’m gonna use EditText.setCustomSelectionActionModeCallback (ActionMode.Callback actionModeCallback). According to documentation:
If provided, this ActionMode.Callback will be used to create the ActionMode when text selection is initiated in this View. The standard implementation populates the menu with a subset of Select All, Cut, Copy, Paste, Replace and Share actions, depending on what this View supports.
Default is null.
Added in API level 11.

Down below is the custom implementation of anActionMode.Callback. OnPrepareActionMode is where menu customization is possible, new menu items can be added or the default actions can be removed. For this example, I will remove all menu items except Copy. You can remove only Cut and Paste menu items with Menu.removeItem(int) passing it android.R.id.cut or android.R.id.paste.

Applying CustomSelectionActionModeCallback to EditText:

So far so good.

2. To completely block a menu which appears when a user taps on cursor I will use EditText.setCustomInsertionActionModeCallback(ActionMode.Callback actionModeCallback). According to documentation

If provided, this ActionMode.Callback will be used to create the ActionMode when text insertion is initiated in this View. The standard implementation populates the menu with a subset of Select All, Paste and Replace actions, depending on what this View supports.
Default is null.
Added in API level 23.

This time ActionMode.Callback implementation will return false from OnCreateActionMode and no menu will be shown at all.

Applying CustomInsertionActionModeCallback to EditText:

3. Block keyboard appearing when a user taps on EditText:

4. Finishing touch to make anEditText look like aTextView in code

or in xml


Check out related articles on how to achieve this behavior on native iOS and Xamarin.Forms.