Webview In Android Project
A Webview is useful when you need increased control over the UI and advanced configuration options that will allow you to embed web pages in a specially-designed environment for your app.
You can add Webview to your app by following simple steps
> create a new android project.
> In the activity_main.xml file add this code for webview and don’t forget to give id to web view.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:layout_marginTop="10dp"
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent">
</WebView>
</LinearLayout>
After adding the above code you can see the preview of the webview in the design panel in the side.
> In the MainActivity.java file you have to add this code.
package com.example.web_view;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView)findViewById(R.id.webview);
webView.loadUrl("https://www.google.co.in");
}
}
NOTE : webView.loadUrl(“ you can add link of any website you want to load here ");
You can get error when you try to run this code now. As to view a webpage in the browser you new internet connection you also need one here.
So we have to give internet permissions. We can do that in the AndroidManifest.xml file.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
You can also get CLEAR TEXT NOT PERMITTED ERROR , in that case in the application section of manifest file add :
android:usesCleartextTraffic="true"
Your manifest file should look like this.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.web_view"><uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:usesCleartextTraffic="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>
Now you can run the code and see the output of web view.
Thank You , Happy Coding !