Reputation: 5512
I am trying to create a custom copy and paste menu in the Action bar but when I select the text in the EditText area the default copy and paste menu will pop up, but when I long press the EditText area instead of the text, the custom menu appears in the Action bar. How can I have my custom copy and paste menu appear when the text is selected?
I looked at this similar question Override the general paste context menu in Android
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText Input = (EditText) findViewById(R.id.Input);
Input.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View p1)
{
// TODO: Implement this method
startActionMode(new ActionBarCallBack());
return false;
}
});
}
class ActionBarCallBack implements ActionMode.Callback
{
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item)
{
// TODO Auto-generated method stub
switch(item.getItemId()) {
case R.id.copyText:
Toast.makeText(getApplicationContext(), "Copy", Toast.LENGTH_SHORT).show();
return true;
case R.id.pasteText:
Toast.makeText(getApplicationContext(), "Paste", Toast.LENGTH_SHORT).show();
return true;
case R.id.cutText:
Toast.makeText(getApplicationContext(), "Cut", Toast.LENGTH_SHORT).show();
return true;
case R.id.help:
Toast.makeText(getApplicationContext(), "Help", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu)
{
// TODO Auto-generated method stub
mode.getMenuInflater().inflate(R.menu.contextual_menu, menu);
return true;
}
@Override
public void onDestroyActionMode(ActionMode mode)
{
// TODO Auto-generated method stub
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu)
{
// TODO Auto-generated method stub
return false;
}
}
}
Upvotes: 2
Views: 7707
Reputation: 300
A full sample bellow. In my case it was to add a "Scan with camera" context menu. Note that this solution doesn't override the context menu of a text selected within the EditText:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
cbEditText.setCustomInsertionActionModeCallback(new ActionMode.Callback() {
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
menu.add(0, 1, 0, R.string.edt_scan_camera);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
if (1 == item.getItemId()) {
//todo: perform your action here!
return true;
}
return false;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
}
});
}
Upvotes: 0
Reputation: 562
Try Using setCustomSelectionActionModeCallback() instead of setOnLongClickListener()
Upvotes: 9