个性化阅读
专注于IT技术分析

android webview例子

本文概述

Android WebView用于在android中显示网页。可以从相同的应用程序或URL加载网页。它用于在android活动中显示在线内容。

Android WebView使用webkit引擎显示网页。

android.webkit.WebView是AbsoluteLayout类的子类。

Android WebView类的loadUrl()和loadData()方法用于加载和显示网页。

Android WebView示例

让我们看一下使用Web视图显示srcmini02.com网页的简单代码。

WebView mywebview = (WebView) findViewById(R.id.webView1);
mywebview.loadUrl("http://www.srcmini02.com/");

让我们看一下使用Web视图显示HTML网页的简单代码。在这种情况下,html文件必须位于资产目录内。

WebView mywebview = (WebView) findViewById(R.id.webView1);
mywebview.loadUrl("file:///android_asset/myresource.html");

让我们看另一个显示字符串的HTML代码的代码。

String data = "<html><body><h1>Hello, srcmini!</h1></body></html>";
mywebview.loadData(data, "text/html", "UTF-8");

完整的Android WebView示例

让我们来看一个完整的Android WebView示例。

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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="example.srcmini02.com.webview.MainActivity">

    <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/webView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

要在应用程序本地添加网页(.html,.jsp),需要将它们放置在资产文件夹中。资产文件夹的创建方式为:右键单击app->新建->文件夹-> Assets文件夹-> main或在主目录中创建资产目录。

活动类

package example.srcmini02.com.webview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WebView mywebview = (WebView) findViewById(R.id.webView);
        // mywebview.loadUrl("https://www.srcmini02.com/");

        /*String data = "<html><body><h1>Hello, srcmini!</h1></body></html>";
        mywebview.loadData(data, "text/html", "UTF-8"); */

        mywebview.loadUrl("file:///android_asset/myresource.html");
    }
}

输出:

让我们看看加载HTML页面的输出。

如果加载srcmini02.com网页,请看输出。

赞(0)
未经允许不得转载:srcmini » android webview例子

评论 抢沙发

评论前必须登录!