搜尋

首頁  >  問答  >  主體

android - 如何修改WebView文本选中时的Contextual Action Bar为Floating Context Menu?

我想实现这种效果:

而选中WebView的文本时,默认是这样的效果:

跪求指点,弄好好几天了。

PHP中文网PHP中文网2772 天前1040

全部回覆(3)我來回復

  • ringa_lee

    ringa_lee2017-04-17 14:33:23

    Update

    最開始的思路:嘗試偵聽WebView文字選取事件以彈出自訂的上下文選單,失敗!
    我找到了一個開源程式碼:BTAndroidWebViewSelection
    有人把這份原始碼封裝成了函式庫:
    Support library for text selection on Android WebView. (forked from BTAndroidWebViewSelection)

    I've Seen a lot of people trying to get user selections with a context menu working in Android web views. The problem lies in Android's use of an intermediate text view that place places between the intermediate text view that 1places between the intermedia on selection. So the javascript in the page doesn't know what's selected.
    This solution uses a javascript interface to pass touches to the page and effectively cut Android's native selection out of the equation. This has the equation.0 has has the equeen to Thied has . .3.

    這應該差不多就是你想要的效果了:

    至於怎麼用,就去看源碼吧


    最開始的思路

    WebView內長按彈出的上下文選單是contextual action mode,也就是你貼的第2張圖,看來應該是WebView預設的特性。而你貼的第1張圖是floating context menu.
    官方文檔menus.html#context-menu

    如果想改變這個預設特性,我能想到的思路是:

    • 定義一個context menu,註冊給你的WebView: registerForContextMenu(View view)
      覆寫context menu的兩個回調函數onCreateContextMenu()onContextItemSelected(),以回應context menuu >這是官方文件給出的實現floating context menu的標準步驟;
      需要說明的是這種方法實現的context menu是一個listview,可能還需要進一步自定義以實現你想要的佈局;

    • 然後需要偵聽到WebView文字選取的事件,以在選取文字後,呼叫

      彈出自訂的floating context menu;Activity.openContextMenu()webview並沒有提供文字選取的listener,所以可能得需要繼承WebView,覆寫它的某些方法.

    • // Step 1
      // Registers a context menu to be shown for the given view.
      registerForContextMenu(mWebView);
      
      // Called when the context menu for this view is being built.
      @Override
      public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
          getMenuInflater().inflate(R.menu.your_custom_context_menu, menu);
      }
      
      // Called whenever an item in a context menu is selected.
      @Override
      public boolean onContextItemSelected(MenuItem item) {
          // do your stuff to respond for menu item selected
          // ...
          return super.onContextItemSelected(item);
      }
      
      // Step 2
      // 可能需要继承webview以在选中文本后弹出context menu
              ...
              // Programmatically opens the context menu for a particular view.
              openContextMenu(v);
              ...
      });
    但是,現在卡在第2步了。即使覆寫WebView,也達不到選取的效果,總是長按WebView就彈出來選項選單。

    回覆
    0
  • 怪我咯

    怪我咯2017-04-17 14:33:23

    LZ,註冊那個為啥不行啊,onCreateContextMenu 這個是自訂哪個類別出現的啊

    回覆
    0
  • 高洛峰

    高洛峰2017-04-17 14:33:23

    lz 請問下,我的需求剛好跟你相反,如何屏蔽系統的Floating Context Menu而改成Contextual Action Bar?我用Crosswalk替換了系統的webview,在android 6.0以下都是現實Contextual Action Bar 但是在android 6.0上卻顯示為Floating Context Menu,想問下如何統一這個?

    回覆
    0
  • 取消回覆