2015-11-07 62 views
-1

我想在網上加載web視圖網頁和離線的時候都沒有網絡它應該會載入上次更新網頁。如何在Android Studio中webView的離線加載?

我已經試過這answer但這並不爲我工作。見截圖http://i.stack.imgur.com/PC4nC.png

這裏是我的源代碼:

public class tab1 extends Fragment { 

WebView webView ; 
ProgressBar progressBar; 
protected File extStorageAppBasePath; 
protected File extStorageAppCachePath; 

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 
    View view=inflater.inflate(R.layout.tab1,container,false); 

    webView = (WebView) view.findViewById(R.id.webview2); 
    progressBar = (ProgressBar)view.findViewById(R.id.progressBar2); 
    webView.setWebChromeClient(new WebChromeClient()); 
    webView.setWebViewClient(new myWebClient()); 
    webView.getSettings().setJavaScriptEnabled(true); 
    webView.loadUrl("http://google.com"); 

    return view; 
} 

public class myWebClient extends WebViewClient 
{ 
    @Override 
    public void onPageStarted(WebView view, String url, Bitmap favicon) { 
     // TODO Auto-generated method stub 
     super.onPageStarted(view, url, favicon); 
    } 

    @Override 
    public boolean shouldOverrideUrlLoading(WebView view, String url) { 
     // TODO Auto-generated method stub 
     progressBar.setVisibility(View.GONE); 
     Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); 
     startActivity(browserIntent); 
     return true; 
    } 

    @Override 
    public void onPageFinished(WebView view, String url) { 
     // TODO Auto-generated method stub 
     super.onPageFinished(view, url); 

     progressBar.setVisibility(View.GONE); 
    } 
} 
} 

回答

2

哎@Ayz阿里你是使用FragmentgetapplicationContextActivity

使用您可以使用getActivity這樣的代碼

WebView webView = new WebView(context); 
webView.getSettings().setAppCacheMaxSize(); 
webView.getSettings().setAppCachePath(getActivity().getCacheDir().getAbsolutePath()); 
webView.getSettings().setAllowFileAccess(true); 
webView.getSettings().setAppCacheEnabled(true); 
webView.getSettings().setJavaScriptEnabled(true); 
webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); // load online by default 

if (!isNetworkAvailable()) { // loading offline 
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); 
} 

webView.loadUrl("http://www.google.com"); 
} 
+0

嘿@amit謝謝你的答案我添加你的代碼,但有一個錯誤,看看這[截圖](http://我.imgur.com/MCECAxH.png) –

+0

@AyzAli哪裏是你'isNetwrokAvailable'方法becoz不能聲明此功能 –

相關問題