public class Main2Activity extends AppCompatActivity {
@BindView(R.id.webView)
WebView webView;
@BindView(R.id.progressBar)
ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
ButterKnife.bind(this);
WebSettings webSettings = webView.getSettings();
webSettings.setUseWideViewPort(true);
webSettings.setLoadsImagesAutomatically(true);
webView.setInitialScale(100);
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
progressBar.setProgress(newProgress);
if (newProgress == 100){
//当100%的时候取消进度条
Toast.makeText(Main2Activity.this, "正在加载"+newProgress, Toast.LENGTH_SHORT).show();
progressBar.setVisibility(WebView.INVISIBLE);
}
}
});
//网址
webView.loadUrl("https://www.baidu.com/");
//在本控件中显示
webView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
}
}
调用js与android的交互
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button button_1;
private WebView webView;
private Button button_2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
button_1 = findViewById(R.id.button_1);
button_2 = (Button) findViewById(R.id.button_2);
webView = findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
//读取本地资源文件中的js文件
webView.loadUrl("file:///android_asset/JavaCalljs1.html");
//在webView界面中显示
webView.setWebChromeClient(new WebChromeClient());
//编码格式
webView.getSettings().setDefaultTextEncodingName("utf-8");
//js调用android的方法
webView.addJavascriptInterface(new JavaButton(), "niejian_android");
button_1.setOnClickListener(this);
}
@SuppressLint("JavascriptInterface")
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_1:
//android调用js方法的方式
webView.loadUrl("javascript:window.niejian_android.javaCallJsMethod1()");
break;
}
}
class JavaButton {
@JavascriptInterface
public void javaCallJsMethod1() {
Toast.makeText(MainActivity.this, "ddd", Toast.LENGTH_SHORT).show();
}
}
}