Web View implementation

Web View is used to help us display a web page in our application without the need to call another application, like web browser, to show designated web page. This android feature can be explained simply as headless browser with no or limited functionality. This web view lives as long the activity is active. It is fairly simple design with just one class for the WebView, and it can be used everywhere in our application.

In my example, im going to use two activities, MainActivity and WebViewActivity, separate layout for every of them, one toolbar layout resource and one logo.

NOTE: Im using ButterKnife library for binding the views, like buttons, text views, edit texts and etc.

First, let`s create MainActivity.class and layout for it:

public class MainActivity extends AppCompatActivity {

In this code we can see only button implementation so we can start our next activity by calling its static method startActivity().

Here is the layout for our activity, activity_main.xml, with one logo, two edit texts and one button, with black background, all of that wrapped in Relative Layout:

Also we need shape for the button in our MainActivity, and its located in drawable under the name shape_button.xml like this:

In the next screen is activity_web_view.xml, the layout for the activity, and it have Toolbar, Web View frame and progress bar over the Web View to be visible when our application is calling the designated web page, and it will be hidden when web page is finished loading:

And for the last, but most important part, initializing the WebViewActivity programmatically. In this activity we have to set up the toolbar for it (not going in to details for that now) in setupToolbar() method, and populating our WebView layout with actual page in setupUi() method for it.
In this setupUi() method we have conditional check if the string, which is URL for the page, passed by our previous activity, in this case MainActivity, is NOT null. Then we start by giving our webView designated URL or web page address with .loadUrl() method which receive String url as a parameter. Then we start our new WebViewClient by calling .setWebViewClient() method passing a new WebViewClient object as a parameter.
Here we have two @overridden methods like onPageFinished() and onReceivedError() where we set our progress bar to INVISIBLE. You can do whatever you like in this methods after the page loading is finished or some error have occurred during page loading:

AndroidManifest (for the action bar implementation)

colors.xml (for the design)

styles.xml (for action bar, or toolbar)

strings.xml (for buttons and edit texts)

Spread the love

Leave a Reply

Your email address will not be published.