Do you know that many apps these days are just JS based? Some apps are fully JS apps while some other apps just embed some webpages into it, even Facebook and Facebook Page are doing it. Well, it is easy and convenient to do. So in this tutorial, I will teach you how embed a webpage into your Navigation Drawer by teaching you to how to use WebView in Fragment in the the latest Android Studio to date.

Here Is A Method That Is Helping How to Use WebView in Fragment in Android Studio

1. Create an Android project and call it WebViewFragment. And my company domain is kosalgeek.com

Then, choose Navigation Drawer Activity

Finally it generates a lot of files:

2. After it built, it generates a lot of files. But you open content_main.xml and change this code:

<?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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.kosalgeek.webviewfragment.MainActivity"
    tools:showIn="@layout/app_bar_main">
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:id="@+id/mainLayout"></LinearLayout>
    </ScrollView>

</LinearLayout>

The most important here in this code is that you need to give a name to a layout because that is the place that a Fragment will go into. In this case, I named it mainLayout in the inner LinearLayout. You can see the code:

android:id=”@+id/mainLayout”

Please note that tools:context=”com.kosalgeek.webviewfragment.MainActivity” includes my project name and company name. You should check your project name and company name and change them here.

3. Create a Fragment, called WebFragment1

Then, name WebFragment1. Make sure to uncheck both checks as you see the screen below:

You should add a WebView in the Fragment as you can see in the screenshot below:

And here is source code of the fragment_web_fragment1.xml layout.

Make sure you give the id to WeView as wvPage1

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.kosalgeek.webviewfragment.WebFragment1">

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

</LinearLayout>

4. Add INTERNET Permission

Open AndroidManifest.xml and add INTERNET Permission:

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

5. Add Fragment Calling Code

Here is the full source code of the MainActivity.java

package com.kosalgeek.webviewfragment;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        showHome();
    }

    private void showHome(){
        fragment = new HomeFragment();
        FragmentManager manager = getSupportFragmentManager();
        manager.beginTransaction().replace(R.id.mainLayout, fragment, fragment.getTag()).commit();
    }

    @Override
    public void onBackPressed() {

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            if(fragment instanceof HomeFragment){
                super.onBackPressed();
            }
            else{
                showHome();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    Fragment fragment = null;

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {

            fragment = new WebFragment1();

        } else if (id == R.id.nav_gallery) {
        } else if (id == R.id.nav_slideshow) {
        } else if (id == R.id.nav_manage) {
        } else if (id == R.id.nav_share) {
        } else if (id == R.id.nav_send) {
        }

        if(fragment != null){
            FragmentManager manager = getSupportFragmentManager();
            manager.beginTransaction().replace(R.id.mainLayout, fragment, fragment.getTag()).commit();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

6. Add WebView Code

Here is the main code to retrieve a webpage. So go to the WebFragment1 again:

package com.kosalgeek.webviewfragment;
import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class WebFragment1 extends Fragment{
    public WebFragment1() {
        // Required empty public constructor
    }

    WebView wvPage1;
    String url = "http://kosalgeek.com";
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.fragment_web_fragment1, container, false);
        wvPage1 = (WebView)v.findViewById(R.id.wvPage1);
        wvPage1.loadUrl(url);
        WebSettings settings = wvPage1.getSettings();
        settings.setJavaScriptEnabled(true);
        wvPage1.setWebViewClient(new MyWebViewClient());
        return v;
    }

    private class MyWebViewClient extends WebViewClient{
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // TODO Auto-generated method stub
            super.onPageStarted(view, url, favicon);
        }

        @SuppressWarnings("deprecation")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            final Uri uri = Uri.parse(url);
            return true;
        }

        @TargetApi(Build.VERSION_CODES.N)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            view.loadUrl(request.getUrl().toString());
            return true;
        }
    }

}

OK, let me break down the code for you. Let’s look at this part:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {         
        View v = inflater.inflate(R.layout.fragment_web_fragment1, container, false);
        wvPage1 = (WebView)v.findViewById(R.id.wvPage1);
        wvPage1.loadUrl(url);
        WebSettings settings = wvPage1.getSettings();
        settings.setJavaScriptEnabled(true);
        wvPage1.setWebViewClient(new MyWebViewClient());
        return v;
}

This line View v = inflater.inflate(R.layout.fragment_web_fragment1, container, false); is important for the Fragment to let you call v.findViewById() method. Unlike in a normal Activity, in Fragment you need to use the inflater class to inflate the fragment on your Activity.

After that line, you will be able to call loadUrl() method with your url. And WebSettings for the Javascript enabler. And after that, you need to set a WebViewClient.

There are some changes for Android N, you need some additional code for Android N:

private class MyWebViewClient extends WebViewClient{
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // TODO Auto-generated method stub
            super.onPageStarted(view, url, favicon);
        }

        @SuppressWarnings("deprecation")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            final Uri uri = Uri.parse(url);
            return true;
        }

        @TargetApi(Build.VERSION_CODES.N)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            view.loadUrl(request.getUrl().toString());
            return true;
        }
    }

You can copy and paste the MyWebViewClient because you won’t change anything here.

DOWNLOAD SOURCE CODE

DOWNLOAD

Comments

comments