How To Implement WebView In Android Studio Using Java || WebView - Android Studio Tutorial [2022]

 


How To Implement WebView In Android Studio Using Java || WebView - Android Studio Tutorial [2022]
In this tutorial we will create simple WebView android app to show a website with loading progressbar. We will pass a new WebViewClient, load a URL and enable JavaScript by changing the WebSettings. We are also going to provide proper back navigation by overriding onBackPressed().
We will start by creating a new project and setting the required properties. Next, we will add a WebView element  and ProgressBar to our layout and configure its properties. Finally, we will write some code to load a website in the WebView. 



MainActiviry.Java

package com.rcube.androidtutorial;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

public class MainActivity extends AppCompatActivity {
private ProgressBar mProgressBar;
private WebView mWebView;

private String urlToload="https://www.roshanaryal.com.np/";

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

//assignviewbyid
mProgressBar = findViewById(R.id.loading_progressbar);
mWebView = findViewById(R.id.webview);

mWebView.loadUrl(urlToload);

mWebView.setWebViewClient(new WebViewClient());
mWebView.getSettings().setJavaScriptEnabled(true);

mWebView.setWebChromeClient(new WebChromeClient(){

@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
mProgressBar.setProgress(newProgress);
}

@Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
getSupportActionBar().setTitle(title);
}
});


}

@Override
public void onBackPressed() {
if (mWebView.canGoBack())
{
mWebView.goBack();
}else {
super.onBackPressed();
}
}
}


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".MainActivity">

<ProgressBar
android:id="@+id/loading_progressbar"
style="@style/Widget.AppCompat.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="4dp" />

<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/loading_progressbar" />


</RelativeLayout>

Thank You.





Post a Comment

0 Comments