Android 3.x ONLY WebView Text Selection + JavaScript

夙愿已清 提交于 2019-11-30 03:54:46

I got this working in 2.2 - 4.0.3. I used a javascript interface and passed all touches to it. The solution seems to work pretty well and I've put an example project on github. The github project includes the necessary js in the assets folder as well as a test page and web view that loads the test page and implements all necessary methods to handle the selection. The link to the github project is https://github.com/btate/BTAndroidWebViewSelection. Have at it.

I'm not 100% sure what methods/properties give you the Range and Selection. I didn't see any in the documentation. But I was able to get the selected range in pixels using reflection. Not sure if this helps anybody, but thought it was worth posting here.

Region result = null;
try {
     Object[] params = null;

     Method nativeGetSelectionRegion = WebView.class.getDeclaredMethod("nativeGetSelectionRegion");
     nativeGetSelectionRegion.setAccessible(true);     
     result = (Region)nativeGetSelectionRegion.invoke(this, params);


     Log.i(TAG, "res: region " + result.getBounds().toShortString());

 } catch (Exception e) {
     e.printStackTrace();
 }

Hopefully that helps somebody

EDIT: This doesn't work on 3.1+

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!