javascript - JavaScript onclick works in browsers, not in Android WebView
问题描述
I have a simple web application, which I'm trying to display through an Android WebView. The webpage consist of not much more than just one HTML table. Each of the cells of said table have an onclick property set to a javascript function, which brings up a box with some information.
This works well in all browsers, both desktop and mobile. However, when I try to click any of the table cells through my Android WebView, nothing happens, the webpage doesn't seem to recognise the clicks.
(Note: I did enable JavaScript for the webview, it does exactly what it should, for example when the document is loaded, only it doesn't recognise the clicks and doesn't fire the corresponding events.)
I've tried searching for an answer, but I had no luck. All threads I found were about solving different problems.
I'm not trying to run Android code by calling a JavaScript function, I only need the website JS to recognize the clicks.
What do I have to do to make this work? Thank you very much in advance, and please don't get too upset if my terminology isn't spot on, I'm just a self-taught enthusiast.
解决方案
原来问题是我setOnTouchListener
用来处理 WebView 点击,即使我确保返回 false 以让 Android 知道点击应该由 WebView 进一步处理,但这并没有发生。我相信这可以通过在代码中的super.OnTouchEvent(event)
某个地方调用来解决,但我不确定我会如何做到这一点,而且我发现了一种非常简单的方法,在我看来它可以更清楚地了解实际发生的情况。
WebView
这个想法是通过扩展和覆盖该onTouchEvent
方法来创建一个自定义的“MyWebView”类:
public class MyWebView extends WebView
{
private GestureDetector mDetector;
public MyWebView(Context context)
{
super(context);
mDetector = new GestureDetector(context, new MyGestureListener());
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
mDetector.onTouchEvent(event);
this.performClick();
return super.onTouchEvent(event);
}
@Override
public boolean performClick()
{
return super.performClick();
}
class MyGestureListener extends GestureDetector.SimpleOnGestureListener
{
@Override public boolean onDown(MotionEvent event)
{
return true;
}
@Override public boolean onSingleTapConfirmed(MotionEvent e)
{
//do stuff here
return false;
}
}
}
推荐阅读
- python - 矩阵的逆 - 工作但一些 0 出现为负数 (-0。)
- javascript - 滑块 - 左右和底部
- delphi - 如何将列宽调整为单元格的内容并允许在 Delphi XE7 中修改宽度?
- c# - OSM 瓦片突然停止下载并抛出异常而不是下载瓦片
- excel - 使用字典减少运行时 VBA
- php - PHP7+ 中的标准类与匿名类
- ui-automation - 除了友好的定位器之外,还有什么方法可以动态地点击空手道中的图标?
- python - 通过python代码从文件中删除灰度图像
- perforce - Perforce:如何查看当前版本和以前版本的更改
- python - 在 s3fs.S3FileSystem 中设置超时的正确方法是什么?