編輯:Android開發教程
下面提供一個android與js互調的簡單示例
(1) android 中 通過該方法調用執行Js中的jsGetTextValue()方法: webview.loadUrl("javascript:jsGetTextValue()");
(2) js中通過addJavascriptInterface設置接口名為jsIntr,然後js中即可直接引用該對象,通過該對象調用java的方法javaSetText();
注意:android4.4以上的版本在addJavascriptInterface中添加的接口方法都必須加上這個前綴 "@android.webkit.JavascriptInterface" ,否則js無法調用java。
1、測試html文件,存放位置 assets / html / test.html
<html>
<body>
<form action="#" method="get">
<p>1 name: <input id="text1" type="text" name="text1" value="1"/></p>
<input type="button" value="button1_value" name="button1_name" onclick="jsGetTextValue()"/>
</form>
<script type="text/javascript">
function jsGetTextValue() {
//js調用java
window.jsIntr.javaSetText(document.getElementById("text1").value);
}
</script>
</body>
</html>
2、android代碼,WebActivity.java
public class WebActivity extends Activity {
private WebView webview;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web);
webview = (WebView) findViewById(R.id.webview);
button = (Button) findViewById(R.id.button);
//允許html執行JS腳本,如果不進行設置的話,JS函數無法生效
webview.getSettings().setJavaScriptEnabled(true); //在設置JS調用java方法的接口對象,在JS中可以直接訪問該對象,然後調用該對象的方法間接地執行java代碼
webview.addJavascriptInterface(new Object() {
@android.webkit.JavascriptInterface
public void javaSetText(String text) {
Log.e("text value", text);
}
//jsIntr是接口名,使用在js中,為調用的java方法的對象
}, "jsIntr");
webview.loadUrl("file:///android_asset/html/test.html");
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//java調用js
webview.loadUrl("javascript:jsGetTextValue()");
}
);
}
}
3、布局文件 activity_web.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Get Value" />
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/button" />
</RelativeLayout>
URL:http://www.bianceng.cn/OS/extra/201609/50431.htm
Android開發入門(十)基本控件 10.2
Button,ImageButton,EditText,ChcekBox,ToggleButton除了最常用的TextView,Android還提供了一些其他的基本控件。
android網絡框架原理
這裡歸納寫一個android網絡框架的一般性原理:Http網絡請求原理學過《計算機網絡》的應該都知道http是一種應用層協議,它通過tcp實現了可靠的數據傳輸,能夠保證數
Android Service服務(三) bindService與remoteService
一、bindService簡介bindService是綁定Service服務,執行service服務中的邏輯流程。service通過 Context.startServi
Android開發入門(十四)顯示圖像 14.1 Gallery和ImageView
Gallery可以顯示一系列的圖片,並且可以橫向滑動。下面展示如何使用Gallery去顯示一系列的圖片。1. 創建一個工程,Gallery。2. main.xml中的代碼