Load webview in fragment from assets
In this
post we will learn about how to open local html file in android studio projects
app or how to load WebView in fragment from using assets folder.
Xml code
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Java Code
webView
= (WebView) view.findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("file:///android_asset/myfile.html");
return view;
Xml code should like this
<?xml version="1.0"
encoding="utf-8"?>
<RelativeLayout
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=".ui.gallery.GalleryFragment">
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Java code should like this
package com.app.androidpro.passiveincomeideas.ui.gallery;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import com.app.androidpro.passiveincomeideas.R;
public class GalleryFragment extends
Fragment {
private WebView
webView;
private GalleryViewModel
galleryViewModel;
public View
onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
//onCreateView(LayoutInflater inflater, ViewGroup
container, Bundle savedInstanceState) {
// View view=inflater.inflate(R.layout.
fragment_gallery, container, false)
View
view=inflater.inflate(R.layout. fragment_gallery, container, false);
webView =
(WebView) view.findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("file:///android_asset/myfile.html");
return view;
}}