不,这不是它的完成方式(您的MyJSInterface 没有constructor 只是为了初学者......)。
这是我的问题。我需要webview,JSInterface 是
附在。
答案是简单地将它传递给构造函数(你已经找到webview)。
第一季度。这是正确的方法吗?这不是循环的,即包含调用它的 WebView 对象的对象的 JSInterface 吗?
是的这是正确的方法。它是不是循环的(或者是递归的,如果这就是你的意思,除非你这样做)。
第二季度。有没有更好的方法来做到这一点?
这就是 Google 设计的方式。有没有更好的方法,只能由找到更好的方法的人来回答,即使这样也是主观的。
我的JSInterface 实现必须包含一个
引用它所附加的WebView!
一点也不奇怪,它是对您需要的对象的引用。
这是记录在案的方式:
WebView webView = findViewById(R.id.wv);
webView.getSettings().setJavaScriptEnabled(true);
// Injects the supplied Java object into this WebView.
// The object is injected into the JavaScript context of the main frame,
// using the supplied name.
// This allows the Java object's public methods to be accessed from JavaScript.
webView.addJavascriptInterface(new JavaScriptInterface(this, webView), "Android");
//===========================================================================
public class JavaScriptInterface
{
Context mContext;
WebView mWebView;
// Instantiate the interface and set the context (constructor)
JavaScriptInterface(Context c, WebView webView)
{
mContext = c;
mWebView = webView;
}
//-----------------
// Show a web page from string
@JavascriptInterface
public void loadWebPage(String page)
{
mWebView.loadUrl("http://www.google.com");
}
//-----------------
// Show a toast from the web page
@JavascriptInterface
public void showToast(String toast)
{
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
//-----------------
//using Javascript to call the finish activity
@JavascriptInterface
public void closeMyActivity()
{
finish();
}
//-----------------
}//class JavaScriptInterface
//===========================================================================
下面是一些使用上述代码的 JavaScript:
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
<input type="button" value="Load Web Page" onClick="loadAndroidWebPage('http://www.google.com')" />
<input type="button" value="Close App" onClick="closeMyActivity()" />
<script type="text/javascript">
function showAndroidToast(toast)
{
Android.showToast(toast);
}
function loadAndroidWebPage(pageURL)
{
Android.loadWebPage(pageURL);
}
function AndroidClose()
{
Android.closeMyActivity();
}
</script>