Context menu (Action Mode) of WebView cannot customized on Android 12

Environment

  • Pixel 3a
  • Android 12 beta 5 (Build No. SPB5.210812.002)

Problem

Usually, context menu of WebView can customized by below.

  1. Create new subclass of WebView.
  2. Override onActionModeStarted() method on the new subclass.
  3. Edit menu of ActionMode class.
@Override
public void onActionModeStarted(ActionMode mode) {
    Menu menu = mode.getMenu();
    
    //  remove "copy" and "select all" menu
    removeMenuItemByTitle(menu, getResources().getString(android.R.string.copy));
    removeMenuItemByTitle(menu, getResources().getString(android.R.string.selectAll));

    //  add new menu
    MenuItem textMarkerMenu = menu.add("Test1");
    MenuItem textMarkerMenu2 = menu.add("Test2");

    super.onActionModeStarted(mode);
}

But, there is no changed on Android 12 by above code.

Solution

You have to call invalidateContentRect() after edit menus.

@Override
public void onActionModeStarted(ActionMode mode) {
    Menu menu = mode.getMenu();
    
    //  remove "copy" and "select all" menu
    removeMenuItemByTitle(menu, getResources().getString(android.R.string.copy));
    removeMenuItemByTitle(menu, getResources().getString(android.R.string.selectAll));

    //  add new menu
    MenuItem textMarkerMenu = menu.add("Test1");
    MenuItem textMarkerMenu2 = menu.add("Test2");

    //  you have to call this.
    mode.invalidateContentRect();

    super.onActionModeStarted(mode);
}

Then, context menu is changed as below. *We remove 3 menus ("copy", "share" and "select all") at following example.

Wrong solution

If you call invalidate() instead of invalidateContentRect(), you can add menu but cannot remove.