天天看點

使用WebView加載本地網頁

  • 效果圖
    使用WebView加載本地網頁
  • 首先将要加載的網頁拷貝到assets目錄下
    使用WebView加載本地網頁

-布局代碼就一個WebView

<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/webView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
           
  • MainActivity代碼
public class MainActivity extends AppCompatActivity {

    private WebView mWebView;

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

        ActionBar supportActionBar = getSupportActionBar();
        if (supportActionBar != null) {
            supportActionBar.setDisplayHomeAsUpEnabled(true);
        }

        mWebView = (WebView) findViewById(R.id.webView);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setDefaultTextEncodingName("UTF-8");

        //防止WebView滾動時背景變成黑色
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
            mWebView.setBackgroundColor(0x00000000);
        } else {
            mWebView.setBackgroundColor(Color.argb(1, 0, 0, 0));
        }

        try {
            mWebView.loadDataWithBaseURL(null, readAssetsFile(getAssets().open("test.html")), "text/html", "utf-8", "");
        } catch (Exception e) {
            Toast.makeText(this, "加載錯誤", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 從輸入流傳回字元串
     * @param inputStream
     * @return
     */
    private String readAssetsFile(InputStream inputStream) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte buf[] = new byte[1024];
        int len;
        try {
            while ((len = inputStream.read(buf)) != -1) {
                outputStream.write(buf, 0, len);
            }
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {

        }
        return outputStream.toString();
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}
           
  • 到這裡就可以愉快的加載本地網頁了,有興趣的同學可以試下哈。