如何在android studio中离线加载webView?

时间:2015-11-07 13:01:59

标签: android webview

我想在没有网络的情况下在线和离线加载webView网页,它应该加载最后更新的网页。

我试过这个https://github.com/graphaware/recommendations-meetup,但这对我不起作用。请参见屏幕截图answer

这是我的源代码:

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

1 个答案:

答案 0 :(得分:2)

嗨@Ayz Ali你使用FragmentgetapplicationContext用于Activity

您可以像这段代码一样使用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" );
 }