Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1
Using WebChromeClient to spruce things up

To hook up the ProgressBar, you will use the second callback on WebView: WebChromeClient.
WebViewClient is an interface for responding to rendering events; WebChromeClient is an event
interface for reacting to events that should change elements of chrome around the browser. This
includes JavaScript alerts, favicons, and of course updates for loading progress and the title of the
current page.


Hook it up in onCreateView(...).


Listing 30.10  Using WebChromeClient (PhotoPageFragment.java)


public class PhotoPageFragment extends VisibleFragment {
...
private WebView mWebView;
private ProgressBar mProgressBar;
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_photo_page, container, false);


mProgressBar = (ProgressBar)v.findViewById(R.id.progress_bar);
mProgressBar.setMax(100); // WebChromeClient reports in range 0-100


mWebView = (WebView) v.findViewById(R.id.web_view);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView webView, int newProgress) {
if (newProgress == 100) {
mProgressBar.setVisibility(View.GONE);
} else {
mProgressBar.setVisibility(View.VISIBLE);
mProgressBar.setProgress(newProgress);
}
}


public void onReceivedTitle(WebView webView, String title) {
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.getSupportActionBar().setSubtitle(title);
}
});
mWebView.setWebViewClient(new WebViewClient());
mWebView.loadUrl(mUri.toString());


return v;
}
}


Progress updates and title updates each have their own callback method,
onProgressChanged(WebView, int) and onReceivedTitle(WebView, String). The progress you
receive from onProgressChanged(WebView, int) is an integer from 0 to 100. If it is 100, you know
that the page is done loading, so you hide the ProgressBar by setting its visibility to View.GONE.

Free download pdf