Javascript 如何从按钮HTML调用活动Android?
我想问一下如何从我的ButtomHTML调用Android Studio上的活动 这是我的按钮html代码:Javascript 如何从按钮HTML调用活动Android?,javascript,java,android,Javascript,Java,Android,我想问一下如何从我的ButtomHTML调用Android Studio上的活动 这是我的按钮html代码: 这是我的java.activity: @覆盖 后期创建时受保护的空(捆绑包savedInstanceState){ super.onPostCreate(savedInstanceState); this.architectView.onPostCreate(); 试一试{ 此.architectView.load(“file:///android_asset/cobarealobj
这是我的java.activity
:
@覆盖
后期创建时受保护的空(捆绑包savedInstanceState){
super.onPostCreate(savedInstanceState);
this.architectView.onPostCreate();
试一试{
此.architectView.load(“file:///android_asset/cobarealobjek/index.html");
}捕获(IOE异常){
e、 printStackTrace();
}
}
这是我的.xml
:
如果您可以选择使用WebView而不是ArchitectView,您可能希望尝试使用
JavascriptInterface
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);
}
}
您必须为接口定义一个类,然后将其绑定到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接口调用函数:
我希望这能有所帮助。它不起作用,只显示白色屏幕。是否可以组合ArchitectView和WebView?您可能需要通过添加标记在android清单中声明internet权限,因为android可能会阻止您的WebView加载网页。