Introduction
Android is one of the most popular operating systems for mobile. The User can access the internet through the Browser. Each Browser has the Web view module. Web view is the most important thing in Android and Web development. Thus, I will show you how to create a Web view Android Application, using Android Studio. Android is a kernel based operating system. It allows the user to modify the GUI components and the source code.
Requirements
- Android Studio.
- Little bit XML and Java knowledge.
- Android emulator (or) an Android mobile.
- Stable internet connection during the execution.
- Download link (Android Studio)
Steps to be followed are given below.
Carefully follow my steps to create Web view Android Application, using Android Studio and I have included the source code given below.
Step 1
Open Android Studio. Start the new project.
Step 2
Put the Application name and the company domain. If you wish to use C++ to code the project, mark Include C++ support, followed by clicking Next.
,
Step 3
Select Android minimum SDK. Afterwards, you chose the minimum SDK. It will show an approximate percentage of the people using the SDK, followed by clicking Next.
Step 4
Choose the basic activity, followed by clicking Next.
Step 5
Put the activity name and the layout name. Android Studio basically takes Java class name, which provides the activity name and click Finish.
Step 6
Go to activity_main.xml, followed by clicking the text bottom. This XML file contains the designing code for an Android app. Into the activity_main.xml, copy and paste the code given below.
Activity_main.xml code
- <?xml version="1.0" encoding="utf-8"?>
- <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:app="http://schemas.android.com/apk/res-auto"
- android:id="@+id/main_content"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:background="@android:color/white"
- android:fitsSystemWindows="true">
-
- <android.support.design.widget.AppBarLayout
- android:id="@+id/appbar"
- android:layout_width="match_parent"
- android:layout_height="@dimen/detail_backdrop_height"
- android:fitsSystemWindows="true"
- android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
-
- <android.support.design.widget.CollapsingToolbarLayout
- android:id="@+id/collapsing_toolbar"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:fitsSystemWindows="true"
- app:contentScrim="?attr/colorPrimary"
- app:expandedTitleMarginEnd="64dp"
- app:expandedTitleMarginStart="48dp"
- app:expandedTitleTextAppearance="@android:color/transparent"
- app:layout_scrollFlags="scroll|exitUntilCollapsed">
-
- <RelativeLayout
- android:layout_width="wrap_content"
- android:layout_height="wrap_content">
-
- <ImageView
- android:id="@+id/backdrop"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:fitsSystemWindows="true"
- android:scaleType="centerCrop"
- app:layout_collapseMode="parallax" />
- </RelativeLayout>
-
- <android.support.v7.widget.Toolbar
- android:id="@+id/toolbar"
- android:layout_width="match_parent"
- android:layout_height="?attr/actionBarSize"
- app:layout_collapseMode="pin"
- app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
-
- </android.support.design.widget.CollapsingToolbarLayout>
-
- </android.support.design.widget.AppBarLayout>
-
- <include layout="@layout/content_main" />
-
- <ProgressBar
- android:id="@+id/progressBar"
- style="@style/Widget.AppCompat.ProgressBar.Horizontal"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_marginTop="-7dp"
- android:indeterminate="true"
- app:layout_behavior="@string/appbar_scrolling_view_behavior" />
-
- </android.support.design.widget.CoordinatorLayout>
Step 7
Create new activity_browser.xml file (File ⇒ New ⇒Activity⇒Empty_activity).
Go to activity_browser.xml, followed by clicking the text bottom. This XML file contains the designing code for an Android app. In activity_browser.xml, copy and paste the code given below.
activity_browser.xml code
- <?xml version="1.0" encoding="utf-8"?>
- <android.support.design.widget.CoordinatorLayout 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:id="@+id/main_content"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:background="@android:color/white"
- android:fitsSystemWindows="true"
- tools:context=".BrowserActivity">
-
- <android.support.design.widget.AppBarLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:theme="@style/AppTheme.AppBarOverlay">
-
- <android.support.v7.widget.Toolbar
- android:id="@+id/toolbar"
- android:layout_width="match_parent"
- android:layout_height="?attr/actionBarSize"
- android:background="?attr/colorPrimary"
- app:popupTheme="@style/AppTheme.PopupOverlay" />
-
- </android.support.design.widget.AppBarLayout>
-
- <include layout="@layout/content_browser_full" />
-
- <ProgressBar
- android:id="@+id/progressBar"
- style="@style/Widget.AppCompat.ProgressBar.Horizontal"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_marginTop="-7dp"
- android:indeterminate="true"
- android:visibility="gone"
- app:layout_behavior="@string/appbar_scrolling_view_behavior" />
-
- </android.support.design.widget.CoordinatorLayout>
Step 8
Create new content_browser_full.xml file (File ⇒ New ⇒Activity⇒Empty_activity).
Go to content_browser_full.xml then click the text bottom. This xml file contains the designing code for android app. In content_browser_full.xml, copy and paste the code given below.
content_browser_full.xml code
- <?xml version="1.0" encoding="utf-8"?>
- <android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:app="http://schemas.android.com/apk/res-auto"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:fadeScrollbars="false"
- android:scrollbarFadeDuration="0"
- app:layout_behavior="@string/appbar_scrolling_view_behavior">
-
-
- <WebView
- android:id="@+id/webView"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" />
-
- </android.support.v4.widget.NestedScrollView>
Step 9
In MainActivity.java, copy and paste the code given below. Java programming is the backend language for Android. Do not replace your package name, otherwise the app will not run.
MainActivity.java code
- import android.content.Context;
- import android.content.Intent;
- import android.os.Bundle;
- import android.support.design.widget.AppBarLayout;
- import android.support.design.widget.CollapsingToolbarLayout;
- import android.support.v7.app.AppCompatActivity;
- import android.support.v7.widget.Toolbar;
- import android.text.TextUtils;
- import android.view.MotionEvent;
- import android.view.View;
- import android.webkit.WebChromeClient;
- import android.webkit.WebView;
- import android.webkit.WebViewClient;
- import android.widget.ImageView;
- import android.widget.ProgressBar;
-
- import com.bumptech.glide.Glide;
- import com.bumptech.glide.load.engine.DiskCacheStrategy;
-
- public class MainActivity extends AppCompatActivity {
-
- private String postUrl = "http://www.c-sharpcorner.com/members/ganeshan-n";
- private WebView webView;
- private ProgressBar progressBar;
- private float m_downX;
- private ImageView imgHeader;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
- setSupportActionBar(toolbar);
- getSupportActionBar().setDisplayHomeAsUpEnabled(true);
-
- webView = (WebView) findViewById(R.id.webView);
- progressBar = (ProgressBar) findViewById(R.id.progressBar);
- imgHeader = (ImageView) findViewById(R.id.backdrop);
-
- if (!TextUtils.isEmpty(getIntent().getStringExtra("postUrl"))) {
- postUrl = getIntent().getStringExtra("postUrl");
- }
-
- initWebView();
- initCollapsingToolbar();
- renderPost();
-
- }
-
- private void initWebView() {
- webView.setWebChromeClient(new MyWebChromeClient(this));
- webView.setWebViewClient(new WebViewClient() {
-
- @Override
- public boolean shouldOverrideUrlLoading(WebView view, String url) {
-
- if (Utils.isSameDomain(postUrl, url)) {
- Intent intent = new Intent(MainActivity.this, MainActivity.class);
- intent.putExtra("postUrl", url);
- startActivity(intent);
- } else {
-
- openInAppBrowser(url);
- }
-
- return true;
- }
-
- @Override
- public void onPageFinished(WebView view, String url) {
- super.onPageFinished(view, url);
- progressBar.setVisibility(View.GONE);
- }
- });
- webView.clearCache(true);
- webView.clearHistory();
- webView.getSettings().setJavaScriptEnabled(true);
- webView.setHorizontalScrollBarEnabled(false);
- webView.setOnTouchListener(new View.OnTouchListener() {
- public boolean onTouch(View v, MotionEvent event) {
-
- if (event.getPointerCount() > 1) {
-
- return true;
- }
-
- switch (event.getAction()) {
- case MotionEvent.ACTION_DOWN: {
-
- m_downX = event.getX();
- }
- break;
-
- case MotionEvent.ACTION_MOVE:
- case MotionEvent.ACTION_CANCEL:
- case MotionEvent.ACTION_UP: {
-
- event.setLocation(m_downX, event.getY());
- }
- break;
-
- }
-
- return false;
- }
- });
- }
-
- private void renderPost() {
- webView.loadUrl(postUrl);
-
- }
-
- private void openInAppBrowser(String url) {
- Intent intent = new Intent(MainActivity.this, BrowserActivity.class);
- intent.putExtra("url", url);
- startActivity(intent);
- }
- private void initCollapsingToolbar() {
- final CollapsingToolbarLayout collapsingToolbar =
- (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
- collapsingToolbar.setTitle(" ");
- AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appbar);
- appBarLayout.setExpanded(true);
-
-
- appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
- boolean isShow = false;
- int scrollRange = -1;
-
- @Override
- public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
- if (scrollRange == -1) {
- scrollRange = appBarLayout.getTotalScrollRange();
- }
- if (scrollRange + verticalOffset == 0) {
- collapsingToolbar.setTitle("Web View");
- isShow = true;
- } else if (isShow) {
- collapsingToolbar.setTitle(" ");
- isShow = false;
- }
- }
- });
-
-
- Glide.with(getApplicationContext()).load("http://www.ourlonelyuniverse.com/wp-content/uploads/2016/01/google-dont-be-evil.png")
- .thumbnail(0.5f)
- .crossFade()
- .diskCacheStrategy(DiskCacheStrategy.ALL)
- .into(imgHeader);
- }
-
- private class MyWebChromeClient extends WebChromeClient {
- Context context;
-
- public MyWebChromeClient(Context context) {
- super();
- this.context = context;
- }
-
-
- }
- }
Step 10
Create new BrowserActivity.java file (File ⇒ New ⇒Java class).
In the BrowserActivity.java, copy and paste the code given below. Java programming is the backend language for an Android. Do not replace your package name, otherwise the app will not run.
BrowserActivity.java code
- import android.content.Context;
- import android.graphics.Bitmap;
- import android.os.Bundle;
- import android.support.design.widget.CoordinatorLayout;
- import android.support.design.widget.Snackbar;
- import android.support.v7.app.AppCompatActivity;
- import android.support.v7.widget.Toolbar;
- import android.text.TextUtils;
- import android.view.Menu;
- import android.view.MenuItem;
- import android.view.MotionEvent;
- import android.view.View;
- import android.webkit.WebChromeClient;
- import android.webkit.WebResourceError;
- import android.webkit.WebResourceRequest;
- import android.webkit.WebView;
- import android.webkit.WebViewClient;
- import android.widget.ProgressBar;
-
- public class BrowserActivity extends AppCompatActivity {
-
-
- private String url;
- private WebView webView;
- private ProgressBar progressBar;
- private float m_downX;
- CoordinatorLayout coordinatorLayout;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_browser);
- Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
- setSupportActionBar(toolbar);
- getSupportActionBar().setDisplayHomeAsUpEnabled(true);
- getSupportActionBar().setTitle("");
-
- url = getIntent().getStringExtra("url");
-
-
- if (TextUtils.isEmpty(url)) {
- finish();
- }
-
- webView = (WebView) findViewById(R.id.webView);
- progressBar = (ProgressBar) findViewById(R.id.progressBar);
- coordinatorLayout = (CoordinatorLayout) findViewById(R.id.main_content);
-
- initWebView();
-
- webView.loadUrl(url);
- }
-
- private void initWebView() {
- webView.setWebChromeClient(new MyWebChromeClient(this));
- webView.setWebViewClient(new WebViewClient() {
- @Override
- public void onPageStarted(WebView view, String url, Bitmap favicon) {
- super.onPageStarted(view, url, favicon);
- progressBar.setVisibility(View.VISIBLE);
- invalidateOptionsMenu();
- }
-
- @Override
- public boolean shouldOverrideUrlLoading(WebView view, String url) {
- webView.loadUrl(url);
- return true;
- }
-
- @Override
- public void onPageFinished(WebView view, String url) {
- super.onPageFinished(view, url);
- progressBar.setVisibility(View.GONE);
- invalidateOptionsMenu();
- }
-
- @Override
- public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
- super.onReceivedError(view, request, error);
- progressBar.setVisibility(View.GONE);
- invalidateOptionsMenu();
- }
- });
- webView.clearCache(true);
- webView.clearHistory();
- webView.getSettings().setJavaScriptEnabled(true);
- webView.setHorizontalScrollBarEnabled(false);
- webView.setOnTouchListener(new View.OnTouchListener() {
- public boolean onTouch(View v, MotionEvent event) {
-
- if (event.getPointerCount() > 1) {
-
- return true;
- }
-
- switch (event.getAction()) {
- case MotionEvent.ACTION_DOWN: {
-
- m_downX = event.getX();
- }
- break;
-
- case MotionEvent.ACTION_MOVE:
- case MotionEvent.ACTION_CANCEL:
- case MotionEvent.ACTION_UP: {
-
- event.setLocation(m_downX, event.getY());
- }
- break;
- }
-
- return false;
- }
- });
- }
-
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
-
- getMenuInflater().inflate(R.menu.browser, menu);
-
- if (Utils.isBookmarked(this, webView.getUrl())) {
-
- Utils.tintMenuIcon(getApplicationContext(), menu.getItem(0), R.color.colorAccent);
- } else {
- Utils.tintMenuIcon(getApplicationContext(), menu.getItem(0), android.R.color.white);
- }
- return true;
- }
-
-
- @Override
- public boolean onPrepareOptionsMenu(Menu menu) {
- if (!webView.canGoBack()) {
- menu.getItem(1).setEnabled(false);
- menu.getItem(1).getIcon().setAlpha(130);
- } else {
- menu.getItem(1).setEnabled(true);
- menu.getItem(1).getIcon().setAlpha(255);
- }
-
- if (!webView.canGoForward()) {
- menu.getItem(2).setEnabled(false);
- menu.getItem(2).getIcon().setAlpha(130);
- } else {
- menu.getItem(2).setEnabled(true);
- menu.getItem(2).getIcon().setAlpha(255);
- }
-
- return true;
- }
-
-
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
-
- if (item.getItemId() == android.R.id.home) {
- finish();
- }
-
- if (item.getItemId() == R.id.action_bookmark) {
-
- Utils.bookmarkUrl(this, webView.getUrl());
-
- String msg = Utils.isBookmarked(this, webView.getUrl()) ?
- webView.getTitle() + "is Bookmarked!" :
- webView.getTitle() + " removed!";
- Snackbar snackbar = Snackbar
- .make(coordinatorLayout, msg, Snackbar.LENGTH_LONG);
- snackbar.show();
- invalidateOptionsMenu();
- }
-
- if (item.getItemId() == R.id.action_back) {
- back();
- }
-
- if (item.getItemId() == R.id.action_forward) {
- forward();
- }
-
- return super.onOptionsItemSelected(item);
- }
- private void back() {
- if (webView.canGoBack()) {
- webView.goBack();
- }
- }
- private void forward() {
- if (webView.canGoForward()) {
- webView.goForward();
- }
- }
-
- private class MyWebChromeClient extends WebChromeClient {
- Context context;
-
- public MyWebChromeClient(Context context) {
- super();
- this.context = context;
- }
- }
- }
Step 11
Create new Utils.java file (File ⇒ New ⇒Java class).
In Utils.java, copy and paste the code given below. Java programming is the backend language for an Android. Do not replace your package name, otherwise the app will not run.
Utils.java code
- import android.content.Context;
- import android.content.SharedPreferences;
- import android.graphics.PorterDuff;
- import android.graphics.drawable.Drawable;
- import android.support.v4.content.ContextCompat;
- import android.view.MenuItem;
-
- public class Utils {
-
- public static boolean isSameDomain(String url, String url1) {
- return getRootDomainUrl(url.toLowerCase()).equals(getRootDomainUrl(url1.toLowerCase()));
- }
-
- private static String getRootDomainUrl(String url) {
- String[] domainKeys = url.split("/")[2].split("\\.");
- int length = domainKeys.length;
- int dummy = domainKeys[0].equals("www") ? 1 : 0;
- if (length - dummy == 2)
- return domainKeys[length - 2] + "." + domainKeys[length - 1];
- else {
- if (domainKeys[length - 1].length() == 2) {
- return domainKeys[length - 3] + "." + domainKeys[length - 2] + "." + domainKeys[length - 1];
- } else {
- return domainKeys[length - 2] + "." + domainKeys[length - 1];
- }
- }
- }
-
- public static void tintMenuIcon(Context context, MenuItem item, int color) {
- Drawable drawable = item.getIcon();
- if (drawable != null) {
-
-
- drawable.mutate();
- drawable.setColorFilter(ContextCompat.getColor(context, color), PorterDuff.Mode.SRC_ATOP);
- }
- }
-
- public static void bookmarkUrl(Context context, String url) {
- SharedPreferences pref = context.getSharedPreferences("androidhive", 0);
- SharedPreferences.Editor editor = pref.edit();
-
-
- if (pref.getBoolean(url, false)) {
- editor.putBoolean(url, false);
- } else {
- editor.putBoolean(url, true);
- }
-
- editor.commit();
- }
-
- public static boolean isBookmarked(Context context, String url) {
- SharedPreferences pref = context.getSharedPreferences("androidhive", 0);
- return pref.getBoolean(url, false);
- }
- }
Step 12
As we need to make network requests, we need to add internet permission in an AndroidManifest.xml. Add the code given below in an AndroidManifest.xml.
AndroidManifest.xml code
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="info.androidhive.webview" >
-
- <uses-permission android:name="android.permission.INTERNET"/>
-
- <application
- android:allowBackup="true"
- android:icon="@mipmap/ic_launcher"
- android:label="@string/app_name"
- android:supportsRtl="true"
- android:theme="@style/AppTheme.NoActionBar" >
- <activity android:name=".MainActivity" >
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
-
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
-
- <activity android:name=".BrowserActivity"
- android:theme="@style/AppTheme.NoActionBar"></activity>
- </application>
-
- </manifest>
Step 13
This is our user interface of the Application. Click Make project option.
Step 14
Run the Application, followed by choosing a virtual machine. Click OK.
Deliverables
“Google-Don’t be evil” image is the default. If you want to replace the image, I will change the image link.
Below this image is the Web view part. I set the default link, which is my C# Corner profile link. Due to this, it shows my C# Corner profile. link.
Just scroll up the page.
Don’t forgot to like and follow me. If you have any doubts, just comment below.
Source code
https://github.com/GaneshanNT/WebView