How to implement WebView in your Android apps

Implementing Android WebView - androidhunger.com

Hello, everyone! Welcome back to androidhunger.com. Here in this post, I will discuss on how to implement WebView in your android apps. As the name suggests, a WebView is a view which displays web pages in your activities or fragments.

Here in this sample app, I used some buttons which when clicked opens up some webpage and displays it the app’s WebView element.

Project on Github Download the app

I will load the social network pages of android hunger, Facebook, G+, Twitter, and YouTube channel when its related button is clicked.

The layout of the app,

Implementing Android WebView - androidhunger.com

Implementing Android WebView – androidhunger.com

The above screen shows a horizontal scroll view for these 4 buttons. When a button is clicked there, below those buttons is a WebView which shows the appropriate web page.

App Demo:

The layout file now looks,

Now I initialize the buttons and web view in the activity file (MainActivity.java),

Now I will set onClickListeners to these buttons,

Here I will handle this click listener by implementing View.OnClickListener to the MainActivity.

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

So now I will add a new onClick function and use a Switch case to handle each click.

Project on Github Download the app

Here we have some options to enable JavaScript or to load images by default and some other options to set.

The laodUrl() accepts a parameter which is the URL we need to open.

In the above code wv.setWebViewClient(new myWebViewClient()); I used a function myWebVewClient which we need to use with WebViewClient which is defined as below.

So now the app is ready, when I click on any of the buttons, its related web page is displayed below.

Project on Github Download the app

 

Implementing Android WebView - androidhunger.com

Implementing Android WebView – androidhunger.com

Implementing Android WebView - androidhunger.com

Implementing Android WebView – androidhunger.com

Implementing Android WebView - androidhunger.com

Implementing Android WebView – androidhunger.com

Implementing Android WebView - androidhunger.com

Implementing Android WebView – androidhunger.com

App Demo:

Leave a Reply

Your email address will not be published. Required fields are marked *