آموزش رایگان آموزش های کاربردی رابط_کاربری رابط_کاربری_اندروید

Learn to display Web pages on Android by WebView

In the identify of Allah. On this dialogue, we first introduced WebView on Android, after which we'll get to understand how to name and display net and net pages (HTML) on-line and offline.

What’s WebView?

WebView is one other Android-powered widget view (widget). By this View, we will display an internet web page or offline (local) net web page within a consumer's activity. Identical to opening an internet site in a browser like Chrome, except that the consumer sees the online web page inside the program and does not move to an unbiased browser.
WebView permits you to management the content material acquired from the online page. For example, we will determine whether or not JavaScript code (JavaScript) that mixes HTML code with net pages may be run.

WebView purposes on Android

A number of purposes might be cited for this view. Probably the most outstanding examples is the display of online maps like Google Maps. Utilizing WebView is among the simplest and most reasonably priced choices for those who plan to show your organization's location on a map.
Another software is the display of content material that is continuously changing and updating. Quite a lot of outstanding apps (together with Instagram) use a WebView to display the “Terms and Conditions of Use” app. In consequence, the consumer receives the principles on-line and on the Instagram servers by visiting this page (Activity). The advantage of this technique is that there isn’t a need to modify the program itself and release the new model to right and replace the text, and the consumer will see the newest version, with out having to replace the app, every time they want to research this system guidelines.
Or suppose you could have launched a store web site and for some cause (low value, excessive value, and so on.) you can’t make a full app. Here you’ll be able to easily get the identical web site as a cellular app for the consumer. Identical to the consumer enters a browser and enter the tackle of your web site. The one distinction is that there isn’t a want to enter the tackle and the website will probably be loaded as soon as the program is operating.

Notice: Using this function to display an entire website within the type of a cellular app just isn’t an ordinary answer and does not make acceptable consumer experience (UX). Use this answer when there are not any other choices on the table! In this case, the web site must be optimized for quite a lot of display pages, ie the implementation of responsive design is required.

Continuing within the form of a challenge, I’ll familiarize you with WebView and its capabilities.

Build a WebView venture on Android Studio

I create a brand new undertaking on Android Studio referred to as WebView. Choose the default exercise as Empty Activity.
As discussed within the Android Retrofit Library tutorial, for the power to communicate between the app and the network (Web), we’d like to define a permission. So I add the related license to the venture manifesto:

AndroidManifest.xml:








Within the Design UI in the Design Mode, I add the WebView widget to Drag & Drop, both manually and in Text mode, to the Format Tag:

WebView widget on Android Studio

activity_main.xml:


Now fill the Java ActiveX file MainActivity.java as follows:

package deal and.android_studio.webview;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity

    personal WebView mWebView;

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

        mWebView = findViewById (R.id.web_view);

        String siteUrl = “https://android-studio.ir”;
        mWebView.loadUrl (siteUrl);

    

I first created an object of the WebView class with the arbitrary identify mWebView. Then, in the onCreate technique, I related this object to the corresponding view. Here, I'm going to show the https://android-studio.ir tackle on this exercise, which is completed by the loadUrl technique. As the identify implies, Url is loaded into our thoughts. Finally, the content of this tackle is shipped to the mWebView that’s hooked up to the web_view widget.
I run the challenge. If the simulator or system has Internet access and the web site is out there, it should display its content.

WebView in the Android app

The online web page is loaded efficiently in my activity and I can scroll up and down.
If my objective of creating this app is to turn the web site into a cellular app, then maybe the one factor needed to take away ActionBar is how we discovered about how to construct the Toolbar on Android. Just change the fashion of the theme to the Theme.AppCompat.Mild.NoActionBar in the types.xml file:

types.xml:



@ colour / colorPrimary
@ shade / colorPrimaryDark
@ colour / colorAccent

Remove Action Times on Android Studio

Except loadUrl, different methods like canGoBack (), canGoForward (), clearHistory (), getUrl (), getTitle (), and so on. can be utilized to search for every one if wanted.
Originally of the discussion, WebView allows us to management and apply the settings on the elements acquired from the online web page.
For example, executing javascript code (do not make javascript with java) is disabled by default, which won’t open my website's menu. As a result of the opening and shutting submenus are managed and run by the jQuery library, written with javascript.

protected void onCreate (Bundle savedInstanceState)
    tremendous.onCreate (savedInstanceState);
    setContentView (R.format.activity_main);

    mWebView = findViewById (R.id.web_view);

    String siteUrl = “https://android-studio.ir”;
    mWebView.loadUrl (siteUrl);

    mWebView.getSettings (). setJavaScriptEnabled (true);

Utilizing the getSettings () technique, there’s a wide range of options obtainable for every particular technique. As you’ll be able to see in the code above, the javascript code is enabled by utilizing the setJavaScriptEnabled technique and the true value for it. Re-run the undertaking Run or Apply Modifications to replace the simulator modifications:

SetJavaScriptEnabled to enable javascript in WebView

Other strategies are also obtainable to the developer to customize different elements in accordance to their wants:

Methods for getSettings in WebView

For example, the first merchandise within the record (setDefaultFontSize) is used to determine the font measurement.
Or utilizing the following methods, zoom buttons are added to the page:

mWebView.getSettings () .setSupportZoom (true);
mWebView.getSettings () .setBuiltInZoomControls (true);
mWebView.getSettings () .setDisplayZoomControls (true);

SetSupportZoom Zoom in WebView

(Zoom buttons appear when the web page scrolls)
A lot of different options might be managed by the setWebViewClient technique. To raised handle the code, I first create an inbound class with the identify of the mWebViewClient in the activity and after the block of the onCreate technique inheriting from the WebViewClient class:

public class MainActivity extends AppCompatActivity

    personal WebView mWebView;

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

        mWebView = findViewById (R.id.web_view);

        String siteUrl = “https://android-studio.ir”;
        mWebView.loadUrl (siteUrl);

        mWebView.getSettings (). setJavaScriptEnabled (true);

        mWebView.getSettings () .setSupportZoom (true);
        mWebView.getSettings () .setBuiltInZoomControls (true);
        mWebView.getSettings () .setDisplayZoomControls (true);

    

    personal class mWebViewClient extends WebViewClient

    

The first technique I add to this class is to handle the clicks on the links on the online web page. Click on the link on one among my website's content material:

WebView Browser Tester

You'll see that the new page is open in the form of a browser referred to as WebView Browser Tester, which is not very fascinating. The tactic shouldOverrideUrlLoading masses the hyperlinks immediately into and out of your net browser and is not transmitted to one other browser.

ShouldOverrideUrlLoading in WebView

From the listing of strategies I choose the enter parameters of the sort WebView with the identify of the view and the string named url. This technique is taken into account to be deprecated by Android with these two parameters, nevertheless it nonetheless stays to be used.

personal class mWebViewClient extends WebViewClient

    @Override
    public boolean shouldOverrideUrlLoading (WebView view, String url)

        view.loadUrl (url);
        return true;

    

I modified and accomplished the tactic. Now, by touching or clicking on each link, the url loaded by loadUrl is loaded and passed to the view, which can cause the brand new page to be displayed instantly inside WebView.
Before implementing and testing this technique, I introduce two other extensively used methods. The onPageStarted and onPageFinished methods return the loading time and the top of the process, respectively.

personal class mWebViewClient extends WebViewClient

    @Override
    public boolean shouldOverrideUrlLoading (WebView view, String url)

        view.loadUrl (url);
        return true;

    

    @Override
    public void onPageStarted (WebView view, String url, Bitmap favicon)
        tremendous.onPageStarted (view, url, favicon);
    

    @Override
    public void onPageFinished (WebView view, String url)
        tremendous.onPageFinished (view, url);
    
    

For example, you’ll be able to run a ProgressBar within the onPageStarted technique and stop it onPageFinished. Nevertheless, I exploit Toast to higher perceive and not marginalize the subject:

personal class mWebViewClient extends WebViewClient

    @Override
    public boolean shouldOverrideUrlLoading (WebView view, String url)

        view.loadUrl (url);
        return true;

    

    @Override
    public void onPageStarted (WebView view, String url, Bitmap favicon)

        Toast.makeText (MainActivity.this, “Loading page …”, Toast.LENGTH_SHORT) .show ();

    

    @Override
    public void onPageFinished (WebView view, String url)

        Toast.makeText (MainActivity.this, “Loading finished”, Toast.LENGTH_SHORT) .show ();
        
    

Finally, define the setWebViewClient technique in onCreate and enter it as the mWebViewClient class:

protected void onCreate (Bundle savedInstanceState)
    tremendous.onCreate (savedInstanceState);
    setContentView (R.format.activity_main);

    mWebView = findViewById (R.id.web_view);

    String siteUrl = “https://android-studio.ir”;
    mWebView.loadUrl (siteUrl);

    mWebView.getSettings (). setJavaScriptEnabled (true);

    mWebView.getSettings () .setSupportZoom (true);
    mWebView.getSettings () .setBuiltInZoomControls (true);
    mWebView.getSettings () .setDisplayZoomControls (true);

    mWebView.setWebViewClient (new mWebViewClient ());

Run the undertaking and click on on a link:

Work on the onPageStarted method in WebView

Work on the onPageFinished method in WebView

You see, the new page was loaded inside WebView itself, not a browser. You may as well see loading messages (Loading web page …) and Loading completed (), that are printed in toast format.

Full Supply MainActivity.java:

package deal and.android_studio.webview;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity

    personal WebView mWebView;

    @Override
    protected void onCreate (Bundle savedInstanceState)
        tremendous.onCreate (savedInstanceState);
        setContentView (R.format.activity_main);

        mWebView = findViewById (R.id.web_view);

        String siteUrl = “https://android-studio.ir”;
        mWebView.loadUrl (siteUrl);

        mWebView.getSettings (). setJavaScriptEnabled (true);

        mWebView.getSettings () .setSupportZoom (true);
        mWebView.getSettings () .setBuiltInZoomControls (true);
        mWebView.getSettings () .setDisplayZoomControls (true);

        mWebView.setWebViewClient (new mWebViewClient ());

    

    personal class mWebViewClient extends WebViewClient

        @Override
        public boolean shouldOverrideUrlLoading (WebView view, String url)

            view.loadUrl (url);
            return true;

        

        @Override
        public void onPageStarted (WebView view, String url, Bitmap favicon)

            Toast.makeText (MainActivity.this, “Loading page …”, Toast.LENGTH_SHORT) .present ();

        

        @Override
        public void onPageFinished (WebView view, String url)

            Toast.makeText (MainActivity.this, “Loading finished”, Toast.LENGTH_SHORT) .present ();

        

    

Display local and offline HTML pages in WebView

In the previous part, our content was acquired from an internet url that required Web communication. However in some instances we may have to display content material in the net format and HTML offline. For instance, designing one or more particular pages of an software for a developer that’s acquainted with the design rules of net pages may be simpler to implement in HTML and CSS format than working with Android Layouts. Or, the individual might want to implement a guide app completely by net pages. The content material of those pages is static (static) and does not require a connection to the server.
In this approach, we’ll place information related to net pages within the venture belongings folder. This folder doesn’t exist by default. To construct it, right-click on the app's undertaking construction and click on the trail
New> Folder> Belongings Folder
Comply with the prompts and within the Finish window to create a folder:

Build assets folder in android studio project

Add asset folder to the Android Studio project

This can be executed outdoors the Android Studio surroundings and on the venture location, including this folder:

Build asset folder in operating system file explorer

I created a simple net web page that incorporates a html file and a css:

View local HTML file in Android WebView

Copy these two information and paste into the folder inside the Android Studio or File Explorer:

Add HTML web pages to the assets folder in Android Studio

In the remaining step, to run this native file as an alternative of the url of the website, I exchange the URL of the website in siteUrl:

String siteUrl = “file: ///android_asset/index.html”;

This can run the index.html file in the Android venture folder in WebView:

Show offline webpages in Android WebView

In this venture, I used a quite simple HTML web page to find out how to add net pages to the app, however probably the most complicated net pages (including textual content, image, javascript, and so on.) might be unlimited in Android purposes. win.

Read extra:

https://developer.android.com/reference/android/webkit/WebView
https://developer.android.com/reference/android/webkit/WebSettings
https://developer.android.com/guide/webapps/webview

Observe: The source of the undertaking is inside the Workouts folder