WebView example in Android

WebView in Android

In this tutorial we will learn to implement the WebView in Android Studio with a simple example.

WebView in Android is used to display web pages in your Android Application.

Example: 
  • Create a new project in Android Studio and name it as WebView and copy paste or do the following things that we describe as follows.
  • Add a WebView element in your main xml activity.
File: activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="hss_24.example.com.webview.MainActivity">

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

</LinearLayout>
  • Initialize the WebView in a java file and do the following code.
File: MainActivity.java:
<
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {

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

        // initialize webView and set url
        WebView webView = (WebView)findViewById(R.id.webView);
        webView.loadUrl("http://androidloversnbaig.blogspot.in/");

        // enabling javaScript
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
    }
}
  • Add internet setting in your Manifest file.
Manifest:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="hss_24.example.com.webview">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
  • Add internet setting in your Manifest file.
  • Tats it!!!... Now run the application and enjoy the Webview.
Output:
 

Download project here...

Comments