How To Open A Website in WebView Android

In android, a WebView is a view that loads a website or webpage into it. for example, the webview can be used to pack your website into an app that simply loads your website when the app is launched. there are many uses for webview. the webview can be used to show html content from a folder, offline.

here in this tutorial we will learn how to successfully load and browse a website into your app

Add Permission

For your app to load a website into it, you need to enable internet access permission in your app’s manifest file.

<uses-permission android:name="android.permission.INTERNET"/>

 

Make Layout for WebView

To create a webview in your activity, just enter this xml code into the activity_main.xml

<WebView
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:id="@+id/web1">
</WebView>

The layout code for webview

The full code of webview should look like this

the android id is used to identify this webview, we will need this id to call this webview from MainActivity.java

 

Add Codes in MainActivity java

so we gave internet permission, set up webview and next we need to load a website to our app. to do that, we need add some codes to MainActivity.java

So open MainActivity.java, and add the following lines of codes into it

WebView webView = (WebView)findViewById(R.id.web1);
webView.loadUrl("http://www.google.com");

So we added this code to our app, now our app will try to load the website www.google.com, but it can’t load the website into the WebView, instead, it will try to open other browser in your device and load the website into it, why? because our app needs a WebViewClient, a WebViewClient handles webpage handling and other various web functions inside the webview. so let’s add a WebViewClient to our app

To add WebViewClient to our app, enter this code below the code we already added

webView.setWebViewClient(new WebViewClient());

WebViewClient code

 

Full code of MainActivity

package com.example.myapp.myapplication;


import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

      WebView webView = (WebView)findViewById(R.id.web1);
      webView.loadUrl("http://www.google.com");
        webView.setWebViewClient(new WebViewClient());
}}

the full code of MainActivity.java should look like this. that’s it.

Now you can test your app on your device. it will load the website into it. instead of www.google.com, you can put your website name there. search on this site if you want to add more features such as progress bar to your app.

, ,

Post navigation

Leave a Reply

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