您的位置:首页 > 移动开发

使用WebView加载本地网页

2017-06-27 14:29 363 查看
效果图



首先将要加载的网页拷贝到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;

@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);
}
}


到这里就可以愉快的加载本地网页了,有兴趣的同学可以试下哈。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息