I need to get selected text from webview.
For this, I put this:
webView.loadUrl("javascript:Android.getHtml(window.getSelection().toString())");
In my touch event.
- touch event works well
Android.getHtml
works well (this is javascriptinterface method)window.getSelection
doesn't have any value: it's problem -> in my view, when I touched a word in webview, window.getSelection automatically should contain the text. Am I wrong?
Is there anyone who can have an idea for this?
Very thanks in advance.
Ps: below is my whole code
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_each_news, container, false);
//설정된 인자값을 받는다
String newsAddress = getArguments().getString("newsAddress");
//Start : 받은 주소로 웹뷰를 띄운다...
webView = (WebView) rootView.findViewById(R.id.webView);
// webView.setWebViewClient(new WebViewClient());
webView.setWebViewClient(new WebViewClient() {});
webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true); //자바스크립트 허용여부
webSettings.setLoadWithOverviewMode(true); //웹페이지 웹뷰크기에 맞추기 위한 설정
webSettings.setUseWideViewPort(true); //웹페이지 웹뷰크기에 맞추기 위한 설정
webView.setInitialScale(1); //웹페이지 웹뷰크기에 맞추기 위한 설정
webView.addJavascriptInterface(new MyJavascriptInterface(), "Android"); //자바스크립트 인터페이스 메소드 등록
//url 호출
webView.loadUrl(newsAddress);
webView.setOnTouchListener(this);
//End : 받은 주소로 웹뷰를 띄운다...
return rootView;
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN: {
// Toast.makeText(getContext(),"웹뷰클릭",Toast.LENGTH_LONG).show();
pressStartTime = System.currentTimeMillis();
pressedX = motionEvent.getX();
pressedY = motionEvent.getY();
stayedWithinClickDistance = true;
break;
}
case MotionEvent.ACTION_MOVE: {
if (stayedWithinClickDistance && getDistance(pressedX, pressedY, motionEvent.getX(), motionEvent.getY()) > MAX_CLICK_DISTANCE) {
stayedWithinClickDistance = false;
}
break;
}
case MotionEvent.ACTION_UP: {
long pressDuration = System.currentTimeMillis() - pressStartTime;
if (pressDuration < MAX_CLICK_DURATION && stayedWithinClickDistance) {
// 클릭처리
webView.evaluateJavascript("(function(){return window.getSelection().toString()})()",
new ValueCallback<String>()
{
@Override
public void onReceiveValue(String value)
{
Log.v(TAG, "SelectedText:" + value);
}
});
}
}
}
return false;
}