使用WebView加载本地网页

来源:互联网 发布:网购电影票软件 编辑:程序博客网 时间:2024/05/17 05:14
  • 效果图
    这里写图片描述

  • 首先将要加载的网页拷贝到assets目录下
    这里写图片描述

    -布局代码就一个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;@Overrideprotected 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();}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {    switch (item.getItemId()) {        case android.R.id.home:            finish();            break;        default:            break;    }    return super.onOptionsItemSelected(item);}}
  • 到这里就可以愉快的加载本地网页了,有兴趣的同学可以试下哈。

原创粉丝点击