Search…

WebView trong Android - Phần 1

Nguyễn NghĩaNguyễn Nghĩa
11/11/20203 min read
Hướng dẫn sử dụng WebView để load web trực tiếp trong app Android.

HTML và CSS từ lâu trở thành những thành phần quen thuộc trong lập trình web, hỗ trợ phát triển front-end tạo ra những giao diện tiện ích và đẹp 1 cách dễ dàng hơn. Từ nhu cầu rất lớn về web, Android hỗ trợ tích hợp WebView để hiển thị HTML trên ứng dụng, từ 1 đường dẫn có thể được tải và hiển thị bởi WebView.

Vì sao sử dụng WebView?

  • Khi màn hình thiết kế quá phức tạp, cần rất nhiều ViewGroup như FrameLayout, RelativeLayout, LinearLayout hay những View khác là TextView, ImageView.
  • Hoặc 1 phần mềm bán hàng cần tận dụng những dữ liệu đã có sẵn như những bài blog bán hàng đã được phát hành trước đó trên website bán hàng của doanh nghiệp.
  • Để thoải mái cho người dùng đỡ phải sao chép đường dẫn và dán vào trình duyệt web, có thể mở trực tiếp từ trong app.

Sử dụng WebView để hiển thị 1 trang web

Có 2 cách để sử dụng WebView:

  • Nạp web từ 1 file HTML vào WebView.
  • Nạp web từ 1 đường dẫn vào WebView.

Nạp web từ 1 file HTML vào WebView

Cũng như những cách sử dụng những View khác, viết layout bằng XML hoặc sử dụng các phương thức trên Java như addViewremoveView để tạo layout động.

Ví dụ tạo layout sử dụng WebView với XML.

File main_activity.xml:

<?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.eitguide.demowebview.MainActivity">

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

File index.html nằm trong thư mục assets của Android project với nội dung như sau:

<!DOCTYPE html>
<html>
<head>
    <title>Master WebView in Android (Part 1)</title>
    <style type="text/css">
        body {
            background-color: #1abc9c;
        }

        h1 {
            color: #ffffff;
            font-size: 32px;
            text-align: center;
        }
    </style>
</head>
<body>
    <h1>Learning Android Programming with Eitguide Blog</h1>
</body>
</html>

Để load nội dung HTML lên WebView, sử dụng phương thức loadUrl() của WebView.

package com.eitguide.demowebview;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private WebView webView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView = (WebView)findViewById(R.id.webview);
        // Load local HTML from specific path 
        webView.loadUrl("file:///android_asset/index.html");
    }
}

Nếu trong file HTML có sử dụng JavaScript thì phải enable JavaScript của WebView và thêm dòng lệnh:

webView.getSettings().setJavaScriptEnabled(true);
WebView trong Android - Phần 1
Nạp từ file HTML

Nạp web từ 1 đường dẫn vào WebView

Cũng giống như cách tải HTML từ tập tin trong máy tính, tải 1 trang web có sử dụng WebView tương tự. Ứng dụng có sử dụng internet nên phải khai báo quyền truy cập internet trong AndroidManifest.xml.

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
package com.eitguide.demowebview;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private static final String EITGUIDE_URL = "https://eitguide.net/";
    private WebView webView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView = (WebView)findViewById(R.id.webview);
        webView.getSettings().setJavaScriptEnabled(true);
        // Load local HTML from url
        webView.loadUrl(EITGUIDE_URL);
    }
}
WebView trong Android - Phần 1
Nạp từ đường dẫn

Bài chung series

IO Stream

IO Stream Co., Ltd

developer@iostream.co
383/1 Quang Trung, ward 10, Go Vap district, Ho Chi Minh city
Business license number: 0311563559 issued by the Department of Planning and Investment of Ho Chi Minh City on February 23, 2012

©IO Stream, 2013 - 2025