I have an app where I want to be able to show a TextView (or EditText) that allows the user to select some text, then press a button to have something done with that text. Implementing this on Android versions prior to Honeycomb is no problem but on Honeycomb and above the default long-press action is to show an action bar with Copy/Cut/Paste options. I can intercept long-press to show my own action bar, but then I do not get the text selection handles displayed.
Once I have started my own ActionMode how do I get the text selection handles displayed?
Here is the code I'm using to start the ActionMode, which works except there are no text selection handles displayed:
public boolean onLongClick(View v) {
if(actionMode == null)
actionMode = startActionMode(new QuoteCallback());
return true;
}
class QuoteCallback implements ActionMode.Callback {
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.quote, menu);
return true;
}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch(item.getItemId()) {
case R.id.quote:
Log.d(TAG, "Selected menu");
mode.finish();
// here is where I would grab the selected text
return true;
}
return false;
}
public void onDestroyActionMode(ActionMode mode) {
actionMode = null;
}
}
I figured out the answer to my own question; TextView (and therefore EditText) has a method
setCustomSelectionActionModeCallback()
which should be used instead ofstartActionMode()
. Using this enables customisation of the menu used by TextView for text selection. Sample code:where StyleCallback customises the text selection menu by removing Select All and adding some styling actions:
The XML for the menu additions is:
Above solution is good if you want to customize the options in action bar. But if you want to override action bar copy/Paste etc, below is the code...
Easiest way to do it is to add a line in your main theme style which you have defined in your
application
tag ofAndroidManifest
. Open your theme style and add the following :OR
For example: My theme style which I have defined: