首页 > 解决方案 > 如何从按钮 HTML 调用活动 Android?

问题描述

我想问如何从我的按钮 HTML 调用 Android Studio 上的活动。

这是我的按钮 html 代码:

<button id="button" class="buttonHome" style="background:url(assets/scan.png)"></button>

这是我的java.activity

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    this.architectView.onPostCreate();
    try {

 this.architectView.load("file:///android_asset/cobarealobjek/index.html");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

这是我的.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.geowikitudes.RealObjectActivity">
    <com.wikitude.architect.ArchitectView
        android:id="@+id/architectView_real"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
    </com.wikitude.architect.ArchitectView>
</FrameLayout>

标签: javascriptjavaandroid

解决方案


如果您可以选择使用 WebView 而不是 ArchitectView,您可能需要尝试使用JavascriptInterface.

您必须为您的界面定义一个类,然后将其绑定到您的 WebViewClient,例如AppInterface.

import android.webkit.JavascriptInterface;
import android.content.Context;
import android.content.Intent;

public class AppInterface {
    Context mContext;
    public AppInterface(Context context) {
        mContext = context;
    }

    // This is where you define the methods you want to be able to call from your web app
    // You have to annotate such methods with @JavascriptInterface
    @JavascriptInterface
    public void startMyActivity() {
        Intent intent = new Intent();
        intent.setClass(mContext, SecondActivity.class);  // Assuming SecondActivity is the name of activity you want to open
        mContext.startActivity(intent);
    }
}

在你的主要活动文件中,你可以有这样的东西:

import android.webkit.WebView;
import android.webkit.WebViewClient;

Webview webView;
WebViewClient webVC;
// ...
@Override
public void onCreate(Bundle savedInstanceState) {
    // ...
    webView = (WebView) findViewById(R.id.webview);  // Assuming you have a webview with the id of "webview" defined in your layout
    webVC = WebViewClient();

    webView.setWebViewClient(webVC);
    webView.getSettings().setJavascriptEnabled(true);
    webView.addJavascriptInterface(new AppInterface(this), "Android");  // You can set the second parameter to any other string, just make sure that you change it accordingly in your javascript
    webView.loadUrl("yourURL");
    // ...

}

最后,在您的 HTML/javascript 代码中,您需要通过提供的 javascript 接口调用该函数: <button id="button" class="buttonHome" style="background:url(assets/scan.png)" onclick="Android.startMyActivity();"></button>

我希望这有帮助。


推荐阅读