[英]Android HTML button onclick event
我在本地 HTML 页面中显示了图像,并且有一个用于单击事件的按钮。 单击此按钮时,我需要调用另一个活动。 它正在工作。 但问题是再去一次,然后回到 HTML 页面,图像未显示且应用程序无法运行。
<script language="javascript">
function validClick() {
valid.performClick();
document.getElementById("ok").value = "start";
}
function refuseClick(){
refuse.performClick();
document.getElementById("no").value = "Je refuse";
}
<div>
<button type="button" id="ok"
style="font-weight: 700; margin-right: 20px;" onclick="validClick();">Start</button>
</div>
HTML 页面包含图像:
<li><a class="box" href="products.html" data-transition="fade" > <img src="img/products.png" alt="Products"> <span class="text"> Products</span>
主要活动:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.about_screen);
WebView webview = (WebView) findViewById(R.id.webview);
webview.loadUrl("file:///android_asset/index.html");
valid = new Button(this);
valid.setOnClickListener(this);
refuse = new Button(this);
refuse.setOnClickListener(this);
// Enablejavascript
WebSettings ws = webview.getSettings();
ws.setJavaScriptEnabled(true);
// Add the interface to record javascript events
webview.addJavascriptInterface(valid, "valid");
webview.addJavascriptInterface(refuse, "refuse");
}
@Override
public void onClick(View v) {
if (v.equals(valid)) {
Intent i = new Intent(this, CloudReco.class);
startActivity(i);
} else if (v.equals(refuse)) {
//do Something else }
}
您需要检查代码中的一些事项。
首先,在您的 HTML 中,顶部的<script>
标记没有关闭。 请在最后一个函数定义后添加一个</script>
。
其次,在 Java 中,请在调用loadUrl
之前配置您的 WebView。 应首先注册设置和 JavaScript 接口。
第三,没有必要使用Button
小部件来实现您正在寻找的效果。 像这样的东西应该是完全足够的:
webview.addJavaScriptInterface(new Object() {
@JavaScriptInterface
public void performClick() {
Intent i = new Intent(this, CloudReco.class);
startActivity(i);
}
}, "valid");
和“拒绝”类似。
我用来传递大量 javascript 事件的下一个“奇怪”方法(上次使用的是滚动事件,我还传递了串联的值):
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("button1Event")) {
// button1 was clicked inside webview html
Toast.makeText(context, "Button1WasClicked", Toast.LENGTH_SHORT).show();
return true; //(to avoid a default redirect to the url)
} else if (url.contains("button2Event")) {
// button2 was clicked inside webview html
Toast.makeText(context, "Button2WasClicked", Toast.LENGTH_SHORT).show();
return true; //(to avoid a default redirect to the url)
}
return false;
}
}
HTML 包含一个虚拟的<a>
元素,用于模拟 URLclick,其中 URL 是我们在本机代码中等待的 KEY:
<!DOCTYPE html>
<html>
<body>
<a id='yourLinkID'></a>
<button onclick="myFunction('button1Event')">Button1</button>
<button onclick="myFunction('button2Event')">Button2</button>
<script>
function myFunction(value) {
document.getElementById('yourLinkID').href = 'testtest' + value;
document.getElementById('yourLinkID').click();
// we set the wanted URL and simulate the click
}
</script>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.