Android network technology-simple use of WebView

Preface

  • Android WebView is a special View on the Android platform. It can be used to display web pages. This WebView class can be used to display only an online web page in an app. Of course, it can also be used to develop a browser.
  • So how can this be achieved? In fact, this is implemented by a component called WebView in Android. Next, I will briefly introduce the common usage of WebView.

1 Introduction

WebView is a control based on webkit engine to display web pages.

2. Basic use

The easiest way to use WebView is to display web content directly. There are three steps:
  1. Add access to the network (AndroidManifest.xml)
  2. Add the WebView control in the layout file;
  3. Load the WebView control in the code Display the web page.

2.1 Step 1: Add access to the network permissions (AndroidManifest.xml)
这是前提!这是前提!这是前提!
 <uses-permission android:name="android.permission.INTERNET"/>
2.2 Step 2: Add the WebView control to the layout file
<?xml version="1.0" encoding="utf-8"?>
<linearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
>
    <WebView
        android:id="@+id/wbv_webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
</linearLayout>
2.3 Step 3: Let the WebView control load and display the web page in the code

  java version

public class MainActivity extends AppCompatActivity {
    
    
    WebView webView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView=this.findViewById(R.id.wbv_webView);
        //通过getSettings方法可以设置浏览器的属性
        //setJavaScriptEnabled让webView支持JavaScript脚本
        webView.getSettings().setJavaScriptEnabled(true);
        //保证一个网页跳转另一个网页时,仍在webView中打开
        webView.setWebViewClient(new WebViewClient());
        //展示指定的url网页
        webView.loadUrl("https://www.csdn.net");
    }
}

  kotlin version

class MainActivity : AppCompatActivity() {
    
    
    override fun onCreate(savedInstanceState: Bundle?) {
    
    
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //通过getSettings方法可以设置浏览器的属性
        //setJavaScriptEnabled让webView支持JavaScript脚本
        wbv_webView.settings.javaScriptEnabled = true
        //保证一个网页跳转另一个网页时,仍在webView中打开
        wbv_webView.webViewClient = WebViewClient()
        //展示指定的url网页
        wbv_webView.loadUrl("https://www.csdn.net")
    }
}

The renderings are as follows:


  Of course, this is only the most basic usage of WebView. Here is a blog of a big brother, for those who want to continue to learn Android: the most comprehensive Webview detailed explanation

Guess you like

Origin blog.csdn.net/weixin_45879630/article/details/109056799