Loading...

An Experience about Using Webview in Android Studio 3.0

View: 132    Dowload: 0   Comment: 0   Post by: admin   Category: Android   Fields: Other

Introduction

I am blogging on ngocminhtran.com (using WordPress platform). Like most websites, I want to write an Android application to help viewers have a lot of great experiences with my blog.

Background

I have used Android Studio 3.0 and referred to Android documents.  Layout of my blog can look like this:

Using the Code

If I want to hide HeaderNavigation and Footer, I just use a little bit of JavaScript:

document.getElementsByClassName('header')[0].style.display='none';
document.getElementsByClassName('navigation')[0].style.display='none';      
document.getElementById('footer').style.display='none';

I have used Webview to display my blog on Android devices. The following code will enable JavaScript for Webview and JavaScript code will run when Webview totally loaded:

final WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url)
            {
                 view.loadUrl("javascript:(function() { " +
                         "document.getElementsByClassName('header')[0].style.display='none'; "+
                         "document.getElementsByClassName('navigation')[0].style.display='none'; " +
                         "document.getElementById('footer').style.display='none'; " +
                        "})()");
            }
        });

After hiding some parts of blog’s layout, I want my blog to display on Android devices as follows:

To do this, I have added an ActionBar object:

final ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("ngocminhtran.com");
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#333333")));

 And I have also added an XML file named menuapp.xml in menu folder contained in res folder.

menuapp.xml can look like this:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:id="@+id/blog"

        android:title="@string/Blog"

        app:showAsAction="ifRoom"

        android:orderInCategory="1"

        />
    <item android:id="@+id/ebooks"

        android:title="@string/EBooks"

        app:showAsAction="ifRoom"

        android:orderInCategory="2"/>
</menu>

Overriding onCreateOptionsMenu method to add menu on ActionBar:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menuapp, menu);
    return true;
}

So far, if viewers select the Blog item, Webview will load all posts from Blog category:

If viewers select the Ebooks item, Webview will load ebooks from Ebooks category:

You notice that text color of selected item has changed from white to gray. These features can be archived by overriding onOptionsItemSelected method:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    final ActionBar actionBar = getSupportActionBar();
    final WebView myWebView = (WebView) findViewById(R.id.webview);
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    View view = findViewById(item.getItemId());
    if (view != null && view instanceof TextView) {
        ((TextView) view).setTextColor( Color.DKGRAY );
    }
    switch (item.getItemId()) {
        case R.id.blog:

            myWebView.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageFinished(WebView view, String url)
                {
                    view.loadUrl("javascript:(function() { " +
                            "document.getElementsByClassName('header')[0].style.display='none'; "+
                            "document.getElementsByClassName('navigation')[0].style.display='none'; " +
                            "document.getElementById('footer').style.display='none'; " +
                            "})()");
                }
            });

            myWebView.loadUrl("http://ngocminhtran.com/category/blog");
            actionBar.setDisplayHomeAsUpEnabled(false);
            view = findViewById(R.id.ebooks);
            if (view != null && view instanceof TextView) {
                ((TextView) view).setTextColor( Color.WHITE );
            }
            return true;

        case R.id.ebooks:

            myWebView.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageFinished(WebView view, String url)
                {
                    view.loadUrl("javascript:(function() { " +
                            "document.getElementsByClassName('header')[0].style.display='none'; "+
                            "document.getElementsByClassName('navigation')[0].style.display='none'; " +
                            "document.getElementById('footer').style.display='none'; " +
                            "})()");
                }

            });
            myWebView.loadUrl(" http://ngocminhtran.com/category/ebooks");
            actionBar.setDisplayHomeAsUpEnabled(false);
            view = findViewById(R.id.ebooks);
            view = findViewById(R.id.blog);
            if (view != null && view instanceof TextView) {
                ((TextView) view).setTextColor( Color.WHITE );
            }
            return true;

        default:
            return super.onOptionsItemSelected(item);
    }
}

If viewers select either a post or an ebook, a X sign will occur at left side of ngocminhtran.com title:

To do this, we must respond to touch event by using setOnTouchListener method of Webview:

myWebView.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeAsUpIndicator(R.drawable.ic_close_white_24dp);
        return false;
    }
});

If the Ebooks item is selected, when viewers click the X sign, Webview will go back to the Ebooks category. If the Blog item is selected, when viewers click the X sign, Webview will go back to the Blog category. The features of the X sign can be archived by overriding onSupportNavigateUp method:

@Override
public boolean onSupportNavigateUp() {
    String url="" ;
    WebView myWebView = (WebView) findViewById(R.id.webview);
    WebBackForwardList mWebBackForwardList = myWebView.copyBackForwardList();
    int i =  mWebBackForwardList.getSize();
    while (i > 0){

        url = mWebBackForwardList.getItemAtIndex(i-1).getUrl();
        if (url.equals("https://ngocminhtran.com/category/blog/")||
                url.equals("https://ngocminhtran.com/category/ebooks/"))
        {
            ActionBar actionBar = getSupportActionBar();
            actionBar.setDisplayHomeAsUpEnabled(false);
            break;
        }

       i = i - 1;
    }
    myWebView.loadUrl(url);
    return true;
}

Points of Interest

If you have had Web developer skills before and you are working with Android programming skills now, Webviewis a connector to combine two skill sets together. I hope my article is helpful. You can download my code here.

An Experience about Using Webview in Android Studio 3.0

I am blogging on ngocminhtran.com (using WordPress platform). Like most websites, I want to write an Android application to help viewers have a lot of great experiences with my blog.

Posted on 17-04-2018 

Comment:

To comment you must be logged in members.

Files with category

  • Chat App

    Chat App

    View: 67    Download: 1   Comment: 0

    Category: Android     Fields: none

    This is a Chat App for Android mobile. You can make separate chat with you partner. I'm using Mysql Database and Php code and All APIs are develop on PHP (REST APIs). My whatsApp:+918285672453: Email ID: nirbhayiise@gmail.com

  • Tower Defense 3D

    Tower Defense 3D

    View: 49    Download: 0   Comment: 0

    Category: Android     Fields: Game - Entertainment

    The goal in this game is to protect your territory against the attacking enemies. Place defensive structures on or along their path of attack to prevent them reaching your base. Strategic choice and positioning of defensive elements is an essential...

  • Flap the Bird

    Flap the Bird

    View: 34    Download: 0   Comment: 0

    Category: Android     Fields: Game - Entertainment

    Tap your screen to make the bird fly. While you are flying there are destruction that will stop you. Avoid hitting the floor and flying to high this will deduct your life. You can collect coins and life along the way. For more mobile games and...

  • Bad Santa

    Bad Santa

    View: 42    Download: 0   Comment: 0

    Category: Android     Fields: Game - Entertainment

    This is a simple shooting game where the Bad Santa is shooting the bad snowman and reindeer. You can collect coins and life along the way. For more mobile games and tutorials you can visit this site.

  • Flappy Halloween Game

    Flappy Halloween Game

    View: 37    Download: 0   Comment: 0

    Category: Android     Fields: Game - Entertainment

    Flappy Halloween is a simple game, tap the screen to move the player. Shoot the pumpkin in the ring to gain score. Avoid hitting the flying destructions and falling from the ground. Since the Halloween is coming this game is really perfect to play...

  • Tilt Ball Game

    Tilt Ball Game

    View: 34    Download: 0   Comment: 0

    Category: Android     Fields: Game - Entertainment

    This game is simple you need to tilt your device to make the ball move in your own desired direction. Reach the finish line before the time ends and move to the next level.

  • Tanks Dawn of Steel Game

    Tanks Dawn of Steel Game

    View: 63    Download: 0   Comment: 0

    Category: Android     Fields: Game - Entertainment

    Tanks Dawn of Steel is a shooting game which you have to defend yourself against incoming enemies for as long as you can. For every enemy that you destroy, you will receive a coin as a score. This game will challenge your skills in aiming and...

  • An Experience about Using Webview in Android Studio 3.0

    An Experience about Using Webview in Android Studio 3.0

    View: 132    Download: 0   Comment: 0

    Category: Android     Fields: Other

    I am blogging on ngocminhtran.com (using WordPress platform). Like most websites, I want to write an Android application to help viewers have a lot of great experiences with my blog.

 
File suggestion for you
Loading...
File top downloads
Loading...
Loading...
Codetitle - library source code to share, download the file to the community
Copyright © 2018. All rights reserved. codetitle Develope by Vinagon .Ltd