Fragment 里面加webview 使用笔记

Fragment里面

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    contentView = inflater.inflate(R.layout.fragment_web, container, false);
    web_view = (WebView)contentView.findViewById(R.id.webview);
    initView();
    web_view.loadUrl(url);
    //web_view.loadUrl("file:///android_asset/Demo.html");
    web_view.setWebViewClient(new WebViewClient());

    mProgressBar = (ProgressBar)contentView.findViewById(R.id.progressbar);

    web_view.setWebChromeClient(new WebChromeClient(){
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress != 100) {
                mProgressBar.setProgress(newProgress);
            } else {
                mProgressBar.setVisibility(View.GONE);
            }
        }
    });



    // Inflate the layout for this fragment
    return contentView;
}


设置显示:

private void initView() {
    WebSettings setting = web_view.getSettings();
    setting.setJavaScriptEnabled(true);//支持Js
    setting.setCacheMode(WebSettings.LOAD_DEFAULT);//缓存模式
    //是否支持画面缩放,默认不支持
    setting.setBuiltInZoomControls(true);
    setting.setSupportZoom(true);
    //是否显示缩放图标,默认显示
    setting.setDisplayZoomControls(false);
    //设置网页内容自适应屏幕大小
    setting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING);//注意网上例程很多的是.SINGLE_COLUMN,但调试时发现移动版网站会错位,所以改成
									       //SINGLE_COLUMN


    setting.setUseWideViewPort(true);
    setting.setLoadWithOverviewMode(true);

}
 
  
 
  
MainActivity中设置返回键返回前一个网页
 
  
boolean isEx = false;
public boolean onKeyDown(int keyCode, KeyEvent event) {
    Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment);
    if(fragment instanceof WebFragment){//判断是不是所属Fragment
        webView =(WebView) fragment.getView().findViewById(R.id.webview);
        if(webView.canGoBack())
        {
            webView.goBack();
        }
        else{
            if (!isEx) {
                isEx = true;
                Toast.makeText(getApplicationContext(), "再按一次退出应用", Toast.LENGTH_SHORT).show();
            } else {
                finish();
            }
        }
    }
    return false;
}


返回网页参考 转自:

http://blog.csdn.net/qq_27665781/article/details/49904055

你可能感兴趣的:(android)