Suresh
Suresh

Reputation: 1259

How to override webview's text selection context menu?

I have a requirement like when i long press on the text in my web view by clicking long press, i should set my custom context menu items instead of "select", "select all", "web search".

Please help me.

enter image description here

Would like to override these default "select all", "copy", "share", "web search". in this place wanna place my custom menus.

Upvotes: 6

Views: 6701

Answers (2)

OriginQiu
OriginQiu

Reputation: 31

you can do some custom in activity method: onActionModeStarted(ActionMode mode), just like this:

@Override
public void onActionModeStarted(ActionMode mode) {
    if (mActionMode == null) {
        mActionMode = mode;
        Menu menu = mode.getMenu();
        menu.clear();
        getMenuInflater().inflate(R.menu.YOUR_MENU, menu);
        List<MenuItem> menuItems = new ArrayList<>();
        // get custom menu item
        for (int i = 0; i < menu.size(); i++) {
            menuItems.add(menu.getItem(i));
        }
        menu.clear();
        // reset menu item order
        int size = menuItems.size();
        for (int i = 0; i < size; i++) {
            addMenuItem(menu, menuItems.get(i), i, true);
        }
        super.onActionModeStarted(mode);
    }
}


/**
 * add custom item to menu
 * @param menu
 * @param item
 * @param order
 * @param isClick
 */
private void addMenuItem(Menu menu, MenuItem item, int order, boolean isClick){
    MenuItem menuItem = menu.add(item.getGroupId(),
            item.getItemId(),
            order,
            item.getTitle());
    menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    if (isClick)
        // set custom menu item click
        menuItem.setOnMenuItemClickListener(this);
}

Upvotes: 3

Fernando Mart&#237;nez
Fernando Mart&#237;nez

Reputation: 1077

Unfortunately you need to extend from WebView class and override onCreateContextMenu method.

See Use a custom contextual action bar for WebView text selection

Upvotes: 3

Related Questions