1.jsonstringifyԴ??
jsonstringifyԴ??
webview js之间的交互,项目中马上用到。cocos捕鱼完整源码JS调用java代码效果图
java代码调用javasrcipt代码效果图
index.html代码:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.//EN" ""
});
function sendInfoToJava(){
window.AndroidWebView.showInfoFromJs(share);
}
<!--在android代码中调用此方法-->
function showInfoFromJava(msg){
alert("showInfoFromJava:"+msg);
} </script></head><body la><div id='b'> <input onclick="sendInfoToJava()" type="button" value="sendInfoToJava"/></div></body></html>
布局代码:
<?coreutils 源码bashxml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="/apk/res/android" xmlns:tools="/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.chenjifang.webview.MainActivity"> <Button android:id="@+id/test_btn" android:text="代码中调用web js代码传递参数" android:layout_width="match_parent" android:layout_height="wrap_content" /> <EditText android:id="@+id/test_edt" android:layout_width="match_parent" android:layout_height="wrap_content" /><WebView android:id="@+id/test_webview" android:layout_width="match_parent" android:layout_height="dp"></WebView></LinearLayout>
java代码:
public class MainActivity extends AppCompatActivity { private WebView mWebView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mWebView = (WebView) findViewById(R.id.test_webview); //设置WebView支持JavaScript mWebView.getSettings().setJavaScriptEnabled(true); mWebView.loadUrl("file:///android_asset/index.html"); mWebView.addJavascriptInterface(new JsInterface(this), "AndroidWebView"); //添加客户端支持 mWebView.setWebChromeClient(new WebChromeClient()); findViewById(R.id.test_btn).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {
sendInfoToJs(); }
}); } private class JsInterface { private Context mContext; public JsInterface(Context context) { this.mContext = context; } //在js中调用window.AndroidWebView.showInfoFromJs(name),便会触发此方法。elasticsearch 源码 mye @JavascriptInterface public void showInfoFromJs(String share) {
Toast.makeText(mContext,orge 源码下载 share, Toast.LENGTH_SHORT).show(); }
} //在java中调用js代码 public void sendInfoToJs() {
String msg = ((EditText)findViewById(R.id.test_edt)).getText().toString(); //调用js中的函数:showInfoFromJava(msg) mWebView.loadUrl("javascript:showInfoFromJava('" + msg + "')"); }
总结下,java代码中要设置webview对javascript的activiti 接口源码支持,addJavascriptInterface(new JsInterface(this), "AndroidWebView");//这句代码中的第二个参数是在js访问方法的地址。
window.AndroidWebView.showInfoFromJs(share);
2024-12-28 13:10
2024-12-28 12:39
2024-12-28 12:34
2024-12-28 11:51
2024-12-28 11:15
2024-12-28 11:08