Stack Overflow Asked by Federico Ponzi on November 15, 2021
I have to intercept the touch on the screen, and this is my code:
mWebView = findViewById(R.id.webview);
mWebView.setWebViewClient(new WebViewClient());
mWebView.loadUrl(URL);
mWebView.setOnTouchListener(this);
mWebView.setOnKeyListener(this);
and my listeners:
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
Log.i(TAG, "Hello, touch.");
onTouchEvent();
return false;
}
return false;
}
@Override
public boolean onKey(View view, int i, KeyEvent keyEvent)
{
Log.i(TAG, "Hello, onKey.");
onTouchEvent();
return false;
}
While the on touch is working fine for touches on the screen, it dosen’t intercept the touch event on the keyboard. For this reason, I’ve added the onkeylistener, but it’s not intercepting the key events. As last thing, I don’t care about what is typed, but just if the screen has been touched.
why not trying onkeyDown
?
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webView.canGoBack()){
webView.goBack();
}else{
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
OR
override this method --> onUnhandledKeyEvent (WebView view, KeyEvent event)
more details on:
OR
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
boolean dispatchFirst = super.dispatchKeyEvent(event);
// Listening here for whatever key events you need
if (event.getAction() == KeyEvent.ACTION_UP)
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_SPACE:
case KeyEvent.KEYCODE_ENTER:
// e.g. get space and enter events here
break;
}
return dispatchFirst;
}
NOTE:-
Preventing developers from accessing the events by default was made by Googlers on purpose. Because the key event input isn't the only one anymore. There're gestures, voice and more is coming. Official recommendation is to "stop relying on legacy key events for text entry at all". Check out more details here: https://code.google.com/p/android/issues/detail?id=42904#c15
Answered by Wini on November 15, 2021
If you want to detect keypress then try to override
onKeyPreIme(int keyCode, KeyEvent event);
Answered by Saikrishna Rajaraman on November 15, 2021
With my recent experience of inexplicable and inconsistent behaviour of calling loadUrl() before setWebViewClient() I would try calling loadUrl() AFTER setting ANYTHING to do with a multi-threaded WebView. That includes setOnTouchListener() and setOnKeyListener(). I realise my answer might not help your specific problem - but it might help others who have experienced similar behaviour and are setting things before before calling loadUrl().
Answered by Frost Metoh on November 15, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP