android webview使用

本文详细介绍了如何在Android应用中使用WebView加载网页,并设置了JavaScript支持及网页加载进度监听等功能。通过设置WebViewClient和WebChromeClient,可以实现网页在应用内部加载而非外部浏览器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

activrty:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {
    private WebView webView;
    private AppCompatActivity activity = this;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        webView = (WebView) this.findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true); // 设置支持javascript
        webView.getSettings().setSupportZoom(true); // 设置支持缩放

        webView.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
                activity.setTitle("Loading...");
                activity.setProgress(progress * 100);
                Log.i("mytag", progress + "");
                //System.out.println(progress);
                if (progress == 100) {
                    activity.setTitle(R.string.app_name);
                }
            }
        });
        webView.loadUrl("http://www.baidu.com"); //设置webview的url
        webView.setWebViewClient(new WebViewClient()); // 设置webViewClient,不写这句会在浏览器中打开

    }
}
布局文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.shidaping.jsbridge.MainActivity">

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></WebView>
</RelativeLayout>

调用webView.getSettings.setJavaScriptEnabled(true)来支持javascript

调用setWebChromeClient方法

可以重写WebChromeClient的onProgressChanged方法来监听网页加载进度的改变。WebChromeClient中可重写的方法还有:

onReceivedTitle:获取网页标题

onReceivedIcon: 获取网页图标

onCloseWindow: 关闭WebView

onJsAlert

onJsPrompt

onjsConfirm

更多方法可直接查看java源码

调用setWebViewClient方法

不调用此方法的话,会在新的浏览器窗口中打开url,而不是activity内

WebViewClient可重写的方法有:

onReceiveError

onPageStart

onPageEnd


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值