webView和js交互

145 阅读2分钟

导入网络权限
2.View布局

<LinearLayout 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=".MainActivity"
android:orientation="vertical">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<EditText
android:id="@+id/path_et"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content" />

<Button
android:id="@+id/load"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="加载"
android:onClick="load"/>

</LinearLayout>


<WebView
android:id="@+id/show_wb"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>

<Button
android:id="@+id/call"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="调用js的方法"
android:onClick="call"/>

</LinearLayout>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
3.MainActivity代码

/*
webView创建流程:
1. 添加权限:AndroidManifest.xml中必须添加联网权限,否则会出Web page not available错误。
*/

public class MainActivity extends AppCompatActivity {


private WebView mWebView;

@SuppressLint("JavascriptInterface")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mWebView = findViewById(R.id.show_wb);

WebSettings settings = mWebView.getSettings();

//支持h5
settings.setJavaScriptEnabled(true);
//是否可以缩放
settings.setSupportZoom(true);

mWebView.setWebViewClient(new WebViewClient(){

/**
* 给WebView加一个事件监听对象(WebViewClient)并重写shouldOverrideUrlLoading,
* 可以对网页中超链接按钮的响应
* 当按下某个连接时WebViewClient会调用这个方法,并传递参数:当前响应的的url地址
*/

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {

// 此处可添加一些逻辑:是否拦截此url,自行处理
// 下方2行代码是指在当前的webview中跳转到新的url

view.loadUrl(url);
return true;
}
});

// Android端定义一个方法,给js调用,
// 使用webView对象,调用addJavascriptInterface方法(),
// 第一个参数是写一个类,在这里面提供要暴露的方法,方法前最好加一个注解:@JavascriptInterface,
// 第二个参数是标识字符串,js通过这个标识,调用我们的方法. 在js里面是这样使用的:Android.showToast(content);
mWebView.addJavascriptInterface(new Object(){

@JavascriptInterface
public void showToast (String content){
Toast.makeText(MainActivity.this, "content", Toast.LENGTH_SHORT).show();
}
},"Android");

}

//调用js暴露的方法.格式固定:webView对象.loadUrl("javascript:js方法名(参数)");
public void call(View v) {
mWebView.loadUrl("javascript:changeInputValue('哈哈! ycf 很高兴认识你,我叫如花')");
}

//这是本地的写法
// private static final String HTML_URL = "file:///android_asset/test.html";
private static final String HTML_URL = "http://169.254.53.96:8080/test.html";

//加载本地的文件
public void load(View v){
mWebView.loadUrl(HTML_URL);
}

}
---------------------
作者:家辉,喂
来源:CSDN
原文:blog.csdn.net/jiahui6666/…
版权声明:本文为博主原创文章,转载请附上博文链接!