Android技术总结(002)—— 使用WebView加载本地html网页
效果图。
工程目录。
主要代码。
1、main.xml。
public class MainActivity extends Activity { private static final String TAG = "MainActivity"; // 平台编码 public static String ENCODING = "UTF-8"; // 文件路径 private static final String DATA_PATH = Environment.getDataDirectory() .getAbsolutePath() + "/data/" + "com.sgw.demo" + "/test.html"; // 网络试图 private WebView mWebView; // 标志位,判断网页是否已经复制到本地 private boolean hasCopiedToLocal = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); findViews(); init(); } private void findViews() { mWebView = (WebView) findViewById(R.id.helpWebView); } private void init() { mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.requestFocus(); mWebView.getSettings().setDefaultTextEncodingName(ENCODING); mWebView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { return false; } }); if (hasCopiedToLocal) { mWebView.loadData(readTxtFile(DATA_PATH), "text/html", ENCODING); } else { mWebView.loadUrl("file:///android_asset/test.html"); } } /** * 从文件中读取字符串 */ private String readTxtFile(String strFilePath) { String path = strFilePath; String content = ""; File file = new File(path); if (file.isDirectory()) { Log.d(TAG, "The File doesn't not exist."); } else { try { InputStream instream = new FileInputStream(file); if (instream != null) { InputStreamReader inputreader = new InputStreamReader( instream); BufferedReader buffreader = new BufferedReader(inputreader); String line; while ((line = buffreader.readLine()) != null) { content += line + "\n"; } instream.close(); } } catch (java.io.FileNotFoundException e) { Log.d(TAG, "The File doesn't not exist."); } catch (IOException e) { Log.d(TAG, e.getMessage()); } } return content; }}