Chapter 30 Browsing the Web and WebView
That is it. Start up PhotoGallery and press on a photo. Your browser app should pop up and load the
photo page for the item you pressed (similar to the image on the left in Figure 30.1).
The Harder Way: WebView
Using an implicit intent to display the photo page is easy and effective. But what if you do not want
your app to open the browser?
Often, you want to display web content within your own activities instead of heading off to the
browser. You may want to display HTML that you generate yourself, or you may want to lock down
the browser somehow. For apps that include help documentation, it is common to implement it as
a web page so that it is easy to update. Opening a web browser to a help web page does not look
professional, and it prevents you from customizing behavior or integrating that web page into your own
UI.
When you want to present web content within your own UI, you use the WebView class. We are calling
this the “harder” way here, but it is pretty darned easy. (Anything is hard compared to using implicit
intents.)
The first step is to create a new activity and fragment to display the WebView. Start, as usual, by
defining a layout file and naming it fragment_photo_page.xml. Make ConstraintLayout the top-
level layout. In the visual editor, drag a WebView into the ConstraintLayout as a child. (You will find
WebView under the Containers section.)
Once the WebView is added, add a constraint for every side to its parent. That gives you the following
constraints:
- from the top of WebView to the top of its parent
- from the bottom of WebView to the bottom of its parent
- from the left of WebView to the left of its parent
- from the right of WebView to the right of its parent
Finally, change the height and width to Any Size and change all the margins to 0. Oh, and give your
WebView an ID: web_view.
You may be thinking, “That ConstraintLayout is not useful.” True enough – for the moment. You will
fill it out later in the chapter with additional “chrome.”
Next, get the rudiments of your fragment set up. Create PhotoPageFragment as a subclass of the
VisibleFragment class you created in the last chapter. You will need to inflate your layout file, extract
your WebView from it, and forward along the URL to display as a fragment argument.