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

(gtxtreme123) #1
The Harder Way: WebView

Finally, you need to provide a default implementation of a class called WebViewClient. WebViewClient
is used to respond to rendering events on a WebView. We will discuss this class a bit more after you
enter the code.


Listing 30.9  Loading URL into WebView (PhotoPageFragment.java)


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


mWebView = (WebView) v.findViewById(R.id.web_view);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient());
mWebView.loadUrl(mUri.toString());


return v;
}
}


Loading the URL has to be done after configuring the WebView, so you do that last. Before that, you
turn JavaScript on by calling getSettings() to get an instance of WebSettings and then calling
WebSettings.setJavaScriptEnabled(true). WebSettings is the first of the three ways you can
modify your WebView. It has various properties you can set, like the user agent string and text size.


After that, you add a WebViewClient to your WebView. To know why, let us first address what happens
without a WebViewClient.


A new URL can be loaded in a couple of different ways: The page can tell you to go to another URL
on its own (a redirect), or you can click on a link. Without a WebViewClient, WebView will ask the
activity manager to find an appropriate activity to load the new URL.


This is not what you want to have happen. Many sites (including Flickr’s photo pages) immediately
redirect to a mobile version of the same site when you load them from a phone browser. There is not
much point to making your own view of the page if it is going to fire an implicit intent anyway when
that happens.


If, on the other hand, you provide your own WebViewClient to your WebView, the process works
differently. Instead of asking the activity manager what to do, it asks your WebViewClient. And in the
default WebViewClient implementation, it says, “Go load the URL yourself!” And so the page will
appear in your WebView.


Run PhotoGallery, press an item, and you should see the item’s photo page displayed in the WebView
(just like the image on the right in Figure 30.1).

Free download pdf