Horizontal menu inflater on long click for web view

后端 未结 2 1301
时光取名叫无心
时光取名叫无心 2021-01-18 05:56

I am having a problem with the webview selection on longClick. I already had an implementation of a customized menu that launches on longClick. But the default menu is launc

2条回答
  •  一向
    一向 (楼主)
    2021-01-18 06:51

    This is the solution that worked for me, hope it may be useful for someone.

    The only difference from the previous answer is that I created the menu dynamically, cause the static menu for some reason was not responding to menuItemClicked() function.

    @Override
    public void onActionModeStarted(ActionMode mode) {
        System.out.println("onActionModeStarted");
        if (mActionMode == null)
        {
            mActionMode = mode;
            //mode.setTitle("Dictionary");
            Menu menu = mode.getMenu();
            menu.clear();
            mode.getMenuInflater().inflate(R.menu.menu, menu);
            List 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);
            }
    
        }
    
        //System.out.println("onActionModeStarted");
        super.onActionModeStarted(mode);
    }
    
    
    private void addMenuItem(Menu menu, MenuItem item, int order, boolean isClick){
        final 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(new OnMenuItemClickListener() {
    
                @Override
                public boolean onMenuItemClick(MenuItem item) {
    
                    BookReader.this.menuItemClicked(item);
                    return true;
                }
            });
    }
    
    public void menuItemClicked(MenuItem item)
    {
        System.out.println("menuItemClicked");
    
        switch (item.getItemId())
        {
            case R.id.dict_menu:
                testWV.searchInDict();
                if (mActionMode!=null){
                    mActionMode.finish();
                }
    
                break;
            case R.id.hi_menu:
                testWV.highlightWord();
    
                break;
            case R.id.q_menu:
                testWV.copyQuote();
                if (mActionMode!=null){
                    mActionMode.finish();
                }
                break;
        }
    }
    

提交回复
热议问题