原文地址:http://www.android100.org/html/201502/21/122162.html
import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.widget.ProgressBar; public class WorkFragment extends Fragment { // private WebView webView; // private ProgressBar progressBar; final String url = "https://www.baidu.com/"; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.work_fragment,container,false); final WebView webView = (WebView)view.findViewById(R.id.workWebView); final ProgressBar progressBar = (ProgressBar)view.findViewById(R.id.progressBar); webView.getSettings().setJavaScriptEnabled(true); webView.setWebChromeClient(new WebChromeClient(){ @Override public void onProgressChanged(WebView view, int newProgress) { if (newProgress == 100) { progressBar.setVisibility(View.INVISIBLE); } else { if (View.INVISIBLE == progressBar.getVisibility()) { progressBar.setVisibility(View.VISIBLE); } progressBar.setProgress(newProgress); } super.onProgressChanged(view, newProgress); } }); webView.loadUrl(url); return view; } }
布局文件代码:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <ProgressBar style="?android:attr/progressBarStyleHorizontal" android:layout_width="match_parent" android:layout_height="8dp" android:id="@+id/progressBar" /> <WebView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/workWebView" /> </LinearLayout>