Webview从assets目录加载html

我试图从assets目录加载一个html页面。 我试过了,但是失败了。

public class ViewWeb extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); WebView wv; wv = (WebView) findViewById(R.id.webView1); wv.loadUrl("file:///android_asset/aboutcertified.html"); // fails here setContentView(R.layout.webview); } } 

我在LogCat中没有发现任何错误

在设置Content视图之前,您正在获取WebView,因此wv可能为null。

 public class ViewWeb extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.webview); WebView wv; wv = (WebView) findViewById(R.id.webView1); wv.loadUrl("file:///android_asset/aboutcertified.html"); // now it will not fail here } } 

无论何时创build活动,都必须在超级调用之后添加setcontentview (您的布局)。

如果你在加载你的布局(“ setContentView(your layout) ”)之前添加你的布局ID,那么你得到错误空指针exception

  setContentView(R.layout.webview); webView = (WebView) findViewById(R.id.webView1); wv.loadUrl("file:///android_asset/xyz.html"); 
 protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); WebView wb = new WebView(this); wb.loadUrl("file:///android_asset/index.htm"); setContentView(wb); } keep your .html in `asset` folder 

从这里下载源代码( 从资产android打开html文件 )

activity_main.xml中

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:background="#FFFFFF" android:layout_height="match_parent"> <WebView android:layout_width="match_parent" android:id="@+id/webview" android:layout_height="match_parent" android:layout_margin="10dp"></WebView> </RelativeLayout> 

MainActivity.java

 package com.deepshikha.htmlfromassets; import android.app.ProgressDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.webkit.WebView; import android.webkit.WebViewClient; public class MainActivity extends AppCompatActivity { WebView webview; ProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); } private void init(){ webview = (WebView)findViewById(R.id.webview); webview.loadUrl("file:///android_asset/download.html"); webview.requestFocus(); progressDialog = new ProgressDialog(MainActivity.this); progressDialog.setMessage("Loading"); progressDialog.setCancelable(false); progressDialog.show(); webview.setWebViewClient(new WebViewClient() { public void onPageFinished(WebView view, String url) { try { progressDialog.dismiss(); } catch (Exception e) { e.printStackTrace(); } } }); } }