WebView Android

To display a web page in android loaded from the same application or URL, the WebView is used in Android. Thus, online content can be displayed in an Android activity using the Android WebView which displays a web page using the Webkit engine. In Android, the AbsoluteLayout class has a subclass android.webkit.WebView.

To load and display a web page, the Android WebView class uses its loadUrl() and loadData() methods.

Android WebView Codes:

To display a web page using WebView:

WebView mywebview = (WebView) findViewById(R.id.webView1);  
mywebview.loadUrl("https://www.w3schools.blog/");

To display an HTML web page using WebView:

For this, we need to locate the HTML file inside the asset directory.

WebView mywebview = (WebView) findViewById(R.id.webView1);  
mywebview.loadUrl("file:///android_asset/myresource.html");

To display an HTML code of a string:

String data = "<html><body><h1>Hello World!!</h1></body></html>";  
mywebview.loadData(data, "text/html", "UTF-8");

Android WebView Example:

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context="MainActivity">
 
   <WebView
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:id="@+id/webView"
       app:layout_constraintBottom_toBottomOf="parent"
       app:layout_constraintLeft_toLeftOf="parent"
       app:layout_constraintRight_toRightOf="parent"
       app:layout_constraintTop_toTopOf="parent" />
 
</android.support.constraint.ConstraintLayout>

The web page (.html, .jsp) needs to be placed in the assets folder, to add it locally in an application. To create an assets folder follow the below steps:

 

right-click on app -> New -> Folder -> Assets Folder ->main

OR

Create an assets directory inside the main directory.

Activity class: (File: MainActivity.java)

package com.example.radioapp;
 
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
 
public class MainActivity extends AppCompatActivity {
 
   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       WebView mywebview = (WebView) findViewById(R.id.webView);
 
 
       mywebview.loadUrl("file:///android_asset/myresource.html");
   }
}

Output:

Content Protection by DMCA.com
Please Share