Cách hiển thị tệp html trong studio android

Bạn có thể cung cấp nội dung dựa trên web—chẳng hạn như HTML, JavaScript và CSS—để ứng dụng của bạn sử dụng mà bạn biên dịch tĩnh vào ứng dụng thay vì tìm nạp qua internet

Nội dung trong ứng dụng không yêu cầu truy cập internet hoặc tiêu tốn băng thông của người dùng và nếu nội dung được thiết kế dành riêng cho chỉ dành cho WebView—nghĩa là nội dung đó phụ thuộc vào việc giao tiếp với ứng dụng gốc—thì người dùng không thể vô tình tải nội dung đó vào một

Tuy nhiên, có một số nhược điểm đối với nội dung trong ứng dụng. Cập nhật nội dung dựa trên web yêu cầu gửi bản cập nhật ứng dụng mới và có khả năng nội dung không khớp giữa nội dung trên trang web và nội dung trong ứng dụng trên thiết bị của bạn nếu người dùng có phiên bản ứng dụng lỗi thời

WebViewAssetLoader

private static class LocalContentWebViewClient extends WebViewClientCompat {

    private final WebViewAssetLoader mAssetLoader;

    LocalContentWebViewClient(WebViewAssetLoader assetLoader) {
        mAssetLoader = assetLoader;
    }

    @Override
    @RequiresApi(21)
    public WebResourceResponse shouldInterceptRequest(WebView view,
                                     WebResourceRequest request) {
        return mAssetLoader.shouldInterceptRequest(request.getUrl());
    }

    @Override
    @SuppressWarnings("deprecation") // to support API < 21
    public WebResourceResponse shouldInterceptRequest(WebView view,
                                     String url) {
        return mAssetLoader.shouldInterceptRequest(Uri.parse(url));
    }
}
4 là một cách linh hoạt và hiệu quả để tải nội dung trong ứng dụng trong một đối tượng
private static class LocalContentWebViewClient extends WebViewClientCompat {

    private final WebViewAssetLoader mAssetLoader;

    LocalContentWebViewClient(WebViewAssetLoader assetLoader) {
        mAssetLoader = assetLoader;
    }

    @Override
    @RequiresApi(21)
    public WebResourceResponse shouldInterceptRequest(WebView view,
                                     WebResourceRequest request) {
        return mAssetLoader.shouldInterceptRequest(request.getUrl());
    }

    @Override
    @SuppressWarnings("deprecation") // to support API < 21
    public WebResourceResponse shouldInterceptRequest(WebView view,
                                     String url) {
        return mAssetLoader.shouldInterceptRequest(Uri.parse(url));
    }
}
5. Lớp này hỗ trợ

  • Đang tải nội dung bằng URL HTTP(S) để tương thích với chính sách cùng nguồn gốc
  • Đang tải các nguồn phụ như JavaScript, CSS, hình ảnh và iframe

Bao gồm

private static class LocalContentWebViewClient extends WebViewClientCompat {

    private final WebViewAssetLoader mAssetLoader;

    LocalContentWebViewClient(WebViewAssetLoader assetLoader) {
        mAssetLoader = assetLoader;
    }

    @Override
    @RequiresApi(21)
    public WebResourceResponse shouldInterceptRequest(WebView view,
                                     WebResourceRequest request) {
        return mAssetLoader.shouldInterceptRequest(request.getUrl());
    }

    @Override
    @SuppressWarnings("deprecation") // to support API < 21
    public WebResourceResponse shouldInterceptRequest(WebView view,
                                     String url) {
        return mAssetLoader.shouldInterceptRequest(Uri.parse(url));
    }
}
4 trong tệp hoạt động chính của bạn. Sau đây là một ví dụ về tải nội dung web đơn giản từ thư mục nội dung

Kotlin

private class LocalContentWebViewClient(private val assetLoader: WebViewAssetLoader) : WebViewClientCompat() {
    @RequiresApi(21)
    override fun shouldInterceptRequest(
        view: WebView,
        request: WebResourceRequest
    ): WebResourceResponse? {
        return assetLoader.shouldInterceptRequest(request.url)
    }

    // to support API < 21
    override fun shouldInterceptRequest(
        view: WebView,
        url: String
    ): WebResourceResponse? {
        return assetLoader.shouldInterceptRequest(Uri.parse(url))
    }
}

Java

private static class LocalContentWebViewClient extends WebViewClientCompat {

    private final WebViewAssetLoader mAssetLoader;

    LocalContentWebViewClient(WebViewAssetLoader assetLoader) {
        mAssetLoader = assetLoader;
    }

    @Override
    @RequiresApi(21)
    public WebResourceResponse shouldInterceptRequest(WebView view,
                                     WebResourceRequest request) {
        return mAssetLoader.shouldInterceptRequest(request.getUrl());
    }

    @Override
    @SuppressWarnings("deprecation") // to support API < 21
    public WebResourceResponse shouldInterceptRequest(WebView view,
                                     String url) {
        return mAssetLoader.shouldInterceptRequest(Uri.parse(url));
    }
}

Ứng dụng của bạn nên định cấu hình phiên bản

private static class LocalContentWebViewClient extends WebViewClientCompat {

    private final WebViewAssetLoader mAssetLoader;

    LocalContentWebViewClient(WebViewAssetLoader assetLoader) {
        mAssetLoader = assetLoader;
    }

    @Override
    @RequiresApi(21)
    public WebResourceResponse shouldInterceptRequest(WebView view,
                                     WebResourceRequest request) {
        return mAssetLoader.shouldInterceptRequest(request.getUrl());
    }

    @Override
    @SuppressWarnings("deprecation") // to support API < 21
    public WebResourceResponse shouldInterceptRequest(WebView view,
                                     String url) {
        return mAssetLoader.shouldInterceptRequest(Uri.parse(url));
    }
}
4 để phù hợp với nhu cầu của ứng dụng. Phần tiếp theo có một ví dụ

Tạo nội dung và tài nguyên trong ứng dụng

private static class LocalContentWebViewClient extends WebViewClientCompat {

    private final WebViewAssetLoader mAssetLoader;

    LocalContentWebViewClient(WebViewAssetLoader assetLoader) {
        mAssetLoader = assetLoader;
    }

    @Override
    @RequiresApi(21)
    public WebResourceResponse shouldInterceptRequest(WebView view,
                                     WebResourceRequest request) {
        return mAssetLoader.shouldInterceptRequest(request.getUrl());
    }

    @Override
    @SuppressWarnings("deprecation") // to support API < 21
    public WebResourceResponse shouldInterceptRequest(WebView view,
                                     String url) {
        return mAssetLoader.shouldInterceptRequest(Uri.parse(url));
    }
}
4 dựa vào phiên bản
private static class LocalContentWebViewClient extends WebViewClientCompat {

    private final WebViewAssetLoader mAssetLoader;

    LocalContentWebViewClient(WebViewAssetLoader assetLoader) {
        mAssetLoader = assetLoader;
    }

    @Override
    @RequiresApi(21)
    public WebResourceResponse shouldInterceptRequest(WebView view,
                                     WebResourceRequest request) {
        return mAssetLoader.shouldInterceptRequest(request.getUrl());
    }

    @Override
    @SuppressWarnings("deprecation") // to support API < 21
    public WebResourceResponse shouldInterceptRequest(WebView view,
                                     String url) {
        return mAssetLoader.shouldInterceptRequest(Uri.parse(url));
    }
}
9 để tải tài nguyên tương ứng với một đường dẫn tài nguyên nhất định. Mặc dù bạn có thể triển khai giao diện này để truy xuất tài nguyên khi ứng dụng của mình cần, nhưng thư viện Webkit sẽ gói

  
    
    
  
  
    

This file was loaded from in-app content

Cách hiển thị tệp html trong studio android

0 và

  
    
    
  
  
    

This file was loaded from in-app content

Cách hiển thị tệp html trong studio android

1 để tải nội dung và tài nguyên Android tương ứng

Để bắt đầu, hãy tạo một số nội dung và tài nguyên cho ứng dụng của bạn. Nói chung

  • Các tệp văn bản như HTML, JavaScript và CSS thuộc về nội dung
  • Hình ảnh và các tệp nhị phân khác thuộc về tài nguyên

Để thêm các tệp web dựa trên văn bản vào một dự án, hãy làm như sau

  1. Trong Android Studio, nhấp chuột phải vào ứng dụng > src > thư mục chính rồi chọn Mới > Thư mục

    Cách hiển thị tệp html trong studio android

    Hình 1. Tạo một thư mục nội dung cho dự án của bạn

  2. Đặt tên cho thư mục "tài sản. "

    Cách hiển thị tệp html trong studio android

    Hình 2. Đặt tên cho thư mục tài sản

  3. Bấm chuột phải vào thư mục nội dung rồi bấm Mới > Tệp. Nhập

    
      
        
        
      
      
        

    This file was loaded from in-app content

    Cách hiển thị tệp html trong studio android

    2 và nhấn Return hoặc Enter

    Cách hiển thị tệp html trong studio android

    Hình 3. Tạo các tệp có tên của các mẫu mã sau

  4. Lặp lại bước trước đó để tạo một tệp trống cho

    
      
        
        
      
      
        

    This file was loaded from in-app content

    Cách hiển thị tệp html trong studio android

    3

  5. Điền vào các tệp trống bạn đã tạo với nội dung trong hai mẫu mã tiếp theo

mục lục. html

________số 8_______

biểu định kiểu. css

body {
  background-color: lightblue;
}

Để thêm tệp web dựa trên hình ảnh vào dự án của bạn, hãy làm như sau

  1. Tải xuống tệp

    
      
        
        
      
      
        

    This file was loaded from in-app content

    Cách hiển thị tệp html trong studio android

    4 về máy cục bộ của bạn

  2. Đổi tên tệp thành

    
      
        
        
      
      
        

    This file was loaded from in-app content

    Cách hiển thị tệp html trong studio android

    5

  3. Di chuyển tệp theo cách thủ công vào thư mục

    
      
        
        
      
      
        

    This file was loaded from in-app content

    Cách hiển thị tệp html trong studio android

    6 của dự án trên ổ cứng của bạn

Hình 4 hiển thị hình ảnh bạn đã thêm và văn bản từ các mẫu mã trước đó được hiển thị trong một ứng dụng

Cách hiển thị tệp html trong studio android

hinh 4. Tệp HTML trong ứng dụng và tệp hình ảnh được hiển thị trong ứng dụng

Để hoàn thành ứng dụng, hãy làm như sau

  1. Đăng ký trình xử lý và định cấu hình

    
      
        
        
      
      
        

    This file was loaded from in-app content

    Cách hiển thị tệp html trong studio android

    7 bằng cách thêm đoạn mã sau vào phương thức
    
      
        
        
      
      
        

    This file was loaded from in-app content

    Cách hiển thị tệp html trong studio android

    8

    Kotlin

    val assetLoader = WebViewAssetLoader.Builder()
                           .addPathHandler("/assets/", AssetsPathHandler(this))
                           .addPathHandler("/res/", ResourcesPathHandler(this))
                           .build()
    webView.webViewClient = LocalContentWebViewClient(assetLoader)
    

    Java

    final WebViewAssetLoader assetLoader = new WebViewAssetLoader.Builder()
             .addPathHandler("/assets/", new WebViewAssetLoader.AssetsPathHandler(this))
             .addPathHandler("/res/", new WebViewAssetLoader.ResourcesPathHandler(this))
             .build();
    mWebView.setWebViewClient(new LocalContentWebViewClient(assetLoader));
    

  2. Tải nội dung bằng cách thêm đoạn mã sau vào phương thức

    
      
        
        
      
      
        

    This file was loaded from in-app content

    Cách hiển thị tệp html trong studio android

    8

    Kotlin

    webView.loadUrl("https://appassets.androidplatform.net/assets/index.html")
    

    Java

    mWebView.loadUrl("https://appassets.androidplatform.net/assets/index.html");
    

Kết hợp nội dung trong ứng dụng với các tài nguyên từ trang web của bạn

Ứng dụng của bạn có thể cần tải hỗn hợp nội dung trong ứng dụng và nội dung từ internet, chẳng hạn như trang HTML trong ứng dụng được tạo kiểu bởi CSS của trang web của bạn.

private static class LocalContentWebViewClient extends WebViewClientCompat {

    private final WebViewAssetLoader mAssetLoader;

    LocalContentWebViewClient(WebViewAssetLoader assetLoader) {
        mAssetLoader = assetLoader;
    }

    @Override
    @RequiresApi(21)
    public WebResourceResponse shouldInterceptRequest(WebView view,
                                     WebResourceRequest request) {
        return mAssetLoader.shouldInterceptRequest(request.getUrl());
    }

    @Override
    @SuppressWarnings("deprecation") // to support API < 21
    public WebResourceResponse shouldInterceptRequest(WebView view,
                                     String url) {
        return mAssetLoader.shouldInterceptRequest(Uri.parse(url));
    }
}
4 hỗ trợ trường hợp sử dụng này. Nếu không ai trong số
body {
  background-color: lightblue;
}
1 đã đăng ký có thể tìm thấy tài nguyên cho đường dẫn nhất định, thì WebView sẽ quay lại tải nội dung từ internet. Nếu bạn đang trộn nội dung trong ứng dụng với các tài nguyên từ trang web của mình, hãy đảm bảo dành riêng các đường dẫn thư mục, chẳng hạn như
body {
  background-color: lightblue;
}
2 hoặc
body {
  background-color: lightblue;
}
3, cho các tài nguyên trong ứng dụng. Tránh lưu trữ bất kỳ tài nguyên nào từ trang web của bạn ở những vị trí đó

Kotlin

val assetLoader = WebViewAssetLoader.Builder()
                        .setDomain("example.com") // replace this with your website's domain
                        .addPathHandler("/assets/", AssetsPathHandler(this))
                        .build()

webView.webViewClient = LocalContentWebViewClient(assetLoader)
val inAppHtmlUrl = "https://example.com/assets/index.html"
webView.loadUrl(inAppHtmlUrl)
val websiteUrl = "https://example.com/website/data.json"

// JavaScript code to fetch() content from the same origin
val jsCode = "fetch('$websiteUrl')" +
        ".then(resp => resp.json())" +
        ".then(data => console.log(data));"

webView.evaluateJavascript(jsCode, null)

Java

final WebViewAssetLoader assetLoader = new WebViewAssetLoader.Builder()
           .setDomain("example.com") // replace this with your website's domain
           .addPathHandler("/assets/", new AssetsPathHandler(this))
           .build();

mWebView.setWebViewClient(new LocalContentWebViewClient(assetLoader));
String inAppHtmlUrl = "https://example.com/assets/index.html";
mWebView.loadUrl(inAppHtmlUrl);
String websiteUrl = "https://example.com/website/data.json";

// JavaScript code to fetch() content from the same origin
String jsCode = "fetch('" + websiteUrl + "')" +
      ".then(resp => resp.json())" +
      ".then(data => console.log(data));";

mWebView.evaluateJavascript(jsCode, null);

Xem bản trình diễn WebView trên GitHub để biết ví dụ về trang HTML trong ứng dụng đang tìm nạp dữ liệu JSON được lưu trữ trên web

tảiDataWithBaseURL

Khi ứng dụng của bạn chỉ cần tải một trang HTML và không cần chặn các nguồn phụ, hãy cân nhắc sử dụng , không yêu cầu nội dung ứng dụng. Bạn có thể sử dụng nó như trong mẫu mã sau

Kotlin

private static class LocalContentWebViewClient extends WebViewClientCompat {

    private final WebViewAssetLoader mAssetLoader;

    LocalContentWebViewClient(WebViewAssetLoader assetLoader) {
        mAssetLoader = assetLoader;
    }

    @Override
    @RequiresApi(21)
    public WebResourceResponse shouldInterceptRequest(WebView view,
                                     WebResourceRequest request) {
        return mAssetLoader.shouldInterceptRequest(request.getUrl());
    }

    @Override
    @SuppressWarnings("deprecation") // to support API < 21
    public WebResourceResponse shouldInterceptRequest(WebView view,
                                     String url) {
        return mAssetLoader.shouldInterceptRequest(Uri.parse(url));
    }
}
0

Java

private static class LocalContentWebViewClient extends WebViewClientCompat {

    private final WebViewAssetLoader mAssetLoader;

    LocalContentWebViewClient(WebViewAssetLoader assetLoader) {
        mAssetLoader = assetLoader;
    }

    @Override
    @RequiresApi(21)
    public WebResourceResponse shouldInterceptRequest(WebView view,
                                     WebResourceRequest request) {
        return mAssetLoader.shouldInterceptRequest(request.getUrl());
    }

    @Override
    @SuppressWarnings("deprecation") // to support API < 21
    public WebResourceResponse shouldInterceptRequest(WebView view,
                                     String url) {
        return mAssetLoader.shouldInterceptRequest(Uri.parse(url));
    }
}
1

Chọn giá trị đối số một cách cẩn thận

  • body {
      background-color: lightblue;
    }
    
    5. Đây là URL mà nội dung HTML của bạn sẽ được tải dưới dạng. Đây phải là một URL HTTP(S)
  • body {
      background-color: lightblue;
    }
    
    6. Đây là nội dung HTML bạn muốn hiển thị, dưới dạng chuỗi
  • body {
      background-color: lightblue;
    }
    
    7. Điều này thường nên được đặt thành
    body {
      background-color: lightblue;
    }
    
    8
  • body {
      background-color: lightblue;
    }
    
    9. Điều này không được sử dụng khi
    body {
      background-color: lightblue;
    }
    
    5 là một URL HTTP(S), do đó có thể được đặt thành
    val assetLoader = WebViewAssetLoader.Builder()
                           .addPathHandler("/assets/", AssetsPathHandler(this))
                           .addPathHandler("/res/", ResourcesPathHandler(this))
                           .build()
    webView.webViewClient = LocalContentWebViewClient(assetLoader)
    
    1
  • val assetLoader = WebViewAssetLoader.Builder()
                           .addPathHandler("/assets/", AssetsPathHandler(this))
                           .addPathHandler("/res/", ResourcesPathHandler(this))
                           .build()
    webView.webViewClient = LocalContentWebViewClient(assetLoader)
    
    2. Giá trị này được đặt thành cùng giá trị với
    body {
      background-color: lightblue;
    }
    
    5

Chúng tôi thực sự khuyên bạn nên sử dụng URL HTTP(S) làm

body {
  background-color: lightblue;
}
5, vì điều này đảm bảo ứng dụng của bạn tuân thủ chính sách cùng nguồn gốc

Nếu bạn không thể tìm thấy

body {
  background-color: lightblue;
}
5 phù hợp cho nội dung của mình và muốn sử dụng , bạn phải mã hóa nội dung bằng mã hóa phần trăm hoặc. Chúng tôi thực sự khuyên bạn nên chọn mã hóa Base64 và sử dụng API Android để mã hóa mã này theo chương trình, như được hiển thị trong mẫu mã sau

Kotlin

private static class LocalContentWebViewClient extends WebViewClientCompat {

    private final WebViewAssetLoader mAssetLoader;

    LocalContentWebViewClient(WebViewAssetLoader assetLoader) {
        mAssetLoader = assetLoader;
    }

    @Override
    @RequiresApi(21)
    public WebResourceResponse shouldInterceptRequest(WebView view,
                                     WebResourceRequest request) {
        return mAssetLoader.shouldInterceptRequest(request.getUrl());
    }

    @Override
    @SuppressWarnings("deprecation") // to support API < 21
    public WebResourceResponse shouldInterceptRequest(WebView view,
                                     String url) {
        return mAssetLoader.shouldInterceptRequest(Uri.parse(url));
    }
}
2

Java

private static class LocalContentWebViewClient extends WebViewClientCompat {

    private final WebViewAssetLoader mAssetLoader;

    LocalContentWebViewClient(WebViewAssetLoader assetLoader) {
        mAssetLoader = assetLoader;
    }

    @Override
    @RequiresApi(21)
    public WebResourceResponse shouldInterceptRequest(WebView view,
                                     WebResourceRequest request) {
        return mAssetLoader.shouldInterceptRequest(request.getUrl());
    }

    @Override
    @SuppressWarnings("deprecation") // to support API < 21
    public WebResourceResponse shouldInterceptRequest(WebView view,
                                     String url) {
        return mAssetLoader.shouldInterceptRequest(Uri.parse(url));
    }
}
3

Thận trọng. Theo mặc định,
val assetLoader = WebViewAssetLoader.Builder()
                       .addPathHandler("/assets/", AssetsPathHandler(this))
                       .addPathHandler("/res/", ResourcesPathHandler(this))
                       .build()
webView.webViewClient = LocalContentWebViewClient(assetLoader)
6 dự kiến ​​dữ liệu HTML sẽ được mã hóa theo phần trăm. Mã hóa phần trăm bằng tay dễ bị lỗi và không có API Android nào để thực hiện việc này theo chương trình. Chúng tôi thực sự khuyên bạn nên chuyển sang
body {
  background-color: lightblue;
}
4 để tránh yêu cầu này hoặc sử dụng API Base64 để mã hóa nội dung, như được hiển thị trong mẫu mã trước đó

Làm cách nào để tải nội dung HTML trong Android?

Bước 1 − Tạo dự án mới trong Android Studio, đi tới Tệp ⇒ Dự án mới và điền tất cả các chi tiết cần thiết để tạo dự án mới. Bước 2 – Thêm đoạn mã sau vào res/layout/activity_main. xml . Trong đoạn mã trên, chúng tôi đã xem web để hiển thị nội dung html.

Chúng tôi có thể sử dụng HTML trong Android Studio không?

HTML xử lý các chuỗi HTML thành văn bản theo kiểu có thể hiển thị và sau đó chúng tôi có thể đặt văn bản trong TextView của mình. Chúng tôi cũng có thể sử dụng WebView để hiển thị nội dung HTML. Hiện tại Android không hỗ trợ tất cả các thẻ HTML nhưng nó hỗ trợ tất cả các thẻ chính

Làm cách nào để hiển thị phản hồi HTML trong Android?

Để tải một trang web (hoặc) cấu trúc trang web (HTML,. ) bạn có thể sử dụng WebView trong android. Như trường hợp của bạn nếu bạn nhận được phản hồi html từ trang bị thêm và cần hiển thị trang bằng WebView, bạn có thể sử dụng phản hồi. body() để chuyển đổi thành chuỗi trước, sau đó sử dụng phương thức loadData() trong WebView để hiển thị nội dung .

Làm cách nào để hiển thị HTML trong TextView trong Android?

htmlToTextView. setText(HtmlCompat. fromHtml(htmlText, 0)); Trong đoạn mã trên, chúng tôi đang lấy dữ liệu HTML từ fromHtml() và thêm vào chế độ xem văn bản bằng cách sử dụng setText().