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
Thus there was a set of changes to be done:
- Remove Cut and Paste items from a menu which gets displayed when a user selects some text;
- Hide a menu which is displayed when a user taps on a cursor;
- Block keyboard appearing when a user taps on an
EditTextlook more like a
So let’s make it step by step!
- 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 an
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
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.
ActionMode.Callback implementation will return
OnCreateActionMode and no menu will be shown at all.
3. Block keyboard appearing when a user taps on
4. Finishing touch to make an
EditText look like a
TextView in code