1. 程式人生 > >Android學習筆記 —— Android開發中,不呼叫系統瀏覽器直接在應用中顯示指定網址的內容

Android學習筆記 —— Android開發中,不呼叫系統瀏覽器直接在應用中顯示指定網址的內容

在開發過程中有一個在應用中直接顯示一個網址的內容,而不是呼叫系統瀏覽器顯示。根據網上大神的例子,終於實現了這一功能!現在把這個功能記錄下來,方便以後使用!

首先是xml檔案佈局,就一個簡單的WebView:

activity_webview.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:gravity="center"
        android:textColor="#ff4545"
        android:text="這是訪問的百度首頁"/>

    <WebView
        android:id="@+id/mWebView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="none"/>

</LinearLayout>

接著就是 java 檔案了:

WebViewActivity:

package com.liyu.logistic.activity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.liyu.logistic.R;

/**
 * Created by Administration on 2018/1/22.
 */

public class WebViewActivity extends AppCompatActivity {


    private WebView mWebView;
    private String url = "http://baidu.com";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);

        mWebView = (WebView) findViewById(R.id.mWebView);

        WebSettings setting = mWebView.getSettings();
        setting.setPluginState(WebSettings.PluginState.ON);
        setting.setJavaScriptEnabled(true);
        //設定滾動條的樣式
        mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET);

        //複寫WebViewClient的shouldOverrideUrlLoading()的方法
        //如果需要事件處理返回false,否則返回true.這樣就可以解決問題了
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                lodurl(view, url);
                return false;
            }
        });

        this.mWebView.loadUrl(url);
    }

    public void lodurl(final WebView webView, final String url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                webView.loadUrl(url);
            }
        });
    }
}


當然了,什麼時候都不能忘記測試結果,下面就是測試的結果:


好了,android 應用內直接顯示網址內容的記錄到這基本就結束了。