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. The 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
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.
Android
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.
Android
Step 3
Select Android minimum SDK. Afterward, you chose the minimum SDK. It will show an approximate percentage of the people using the SDK, followed by clicking Next.
Android
Step 4
Choose the basic activity, followed by clicking Next.
Android
Step 5
Put the activity name and the layout name. Android Studio basically takes a Java class name, which provides the activity name and click Finish.
Android
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
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:app="http://schemas.android.com/apk/res-auto"
  4. android:id="@+id/main_content"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. android:background="@android:color/white"
  8. android:fitsSystemWindows="true">
  9. <android.support.design.widget.AppBarLayout
  10. android:id="@+id/appbar"
  11. android:layout_width="match_parent"
  12. android:layout_height="@dimen/detail_backdrop_height"
  13. android:fitsSystemWindows="true"
  14. android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
  15. <android.support.design.widget.CollapsingToolbarLayout
  16. android:id="@+id/collapsing_toolbar"
  17. android:layout_width="match_parent"
  18. android:layout_height="match_parent"
  19. android:fitsSystemWindows="true"
  20. app:contentScrim="?attr/colorPrimary"
  21. app:expandedTitleMarginEnd="64dp"
  22. app:expandedTitleMarginStart="48dp"
  23. app:expandedTitleTextAppearance="@android:color/transparent"
  24. app:layout_scrollFlags="scroll|exitUntilCollapsed">
  25. <RelativeLayout
  26. android:layout_width="wrap_content"
  27. android:layout_height="wrap_content">
  28. <ImageView
  29. android:id="@+id/backdrop"
  30. android:layout_width="match_parent"
  31. android:layout_height="match_parent"
  32. android:fitsSystemWindows="true"
  33. android:scaleType="centerCrop"
  34. app:layout_collapseMode="parallax" />
  35. </RelativeLayout>
  36. <android.support.v7.widget.Toolbar
  37. android:id="@+id/toolbar"
  38. android:layout_width="match_parent"
  39. android:layout_height="?attr/actionBarSize"
  40. app:layout_collapseMode="pin"
  41. app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
  42. </android.support.design.widget.CollapsingToolbarLayout>
  43. </android.support.design.widget.AppBarLayout>
  44. <include layout="@layout/content_main" />
  45. <ProgressBar
  46. android:id="@+id/progressBar"
  47. style="@style/Widget.AppCompat.ProgressBar.Horizontal"
  48. android:layout_width="match_parent"
  49. android:layout_height="wrap_content"
  50. android:layout_marginTop="-7dp"
  51. android:indeterminate="true"
  52. app:layout_behavior="@string/appbar_scrolling_view_behavior" />
  53. </android.support.design.widget.CoordinatorLayout>
Android
Step 7
Create a 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
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:app="http://schemas.android.com/apk/res-auto"
  4. xmlns:tools="http://schemas.android.com/tools"
  5. android:id="@+id/main_content"
  6. android:layout_width="match_parent"
  7. android:layout_height="match_parent"
  8. android:background="@android:color/white"
  9. android:fitsSystemWindows="true"
  10. tools:context=".BrowserActivity">
  11. <android.support.design.widget.AppBarLayout
  12. android:layout_width="match_parent"
  13. android:layout_height="wrap_content"
  14. android:theme="@style/AppTheme.AppBarOverlay">
  15. <android.support.v7.widget.Toolbar
  16. android:id="@+id/toolbar"
  17. android:layout_width="match_parent"
  18. android:layout_height="?attr/actionBarSize"
  19. android:background="?attr/colorPrimary"
  20. app:popupTheme="@style/AppTheme.PopupOverlay" />
  21. </android.support.design.widget.AppBarLayout>
  22. <include layout="@layout/content_browser_full" />
  23. <ProgressBar
  24. android:id="@+id/progressBar"
  25. style="@style/Widget.AppCompat.ProgressBar.Horizontal"
  26. android:layout_width="match_parent"
  27. android:layout_height="wrap_content"
  28. android:layout_marginTop="-7dp"
  29. android:indeterminate="true"
  30. android:visibility="gone"
  31. app:layout_behavior="@string/appbar_scrolling_view_behavior" />
  32. </android.support.design.widget.CoordinatorLayout>
Android
Step 8
Create a 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
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:app="http://schemas.android.com/apk/res-auto"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent"
  6. android:fadeScrollbars="false"
  7. android:scrollbarFadeDuration="0"
  8. app:layout_behavior="@string/appbar_scrolling_view_behavior">
  9. <WebView
  10. android:id="@+id/webView"
  11. android:layout_width="match_parent"
  12. android:layout_height="wrap_content" />
  13. </android.support.v4.widget.NestedScrollView>
Android
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
  1. import android.content.Context;
  2. import android.content.Intent;
  3. import android.os.Bundle;
  4. import android.support.design.widget.AppBarLayout;
  5. import android.support.design.widget.CollapsingToolbarLayout;
  6. import android.support.v7.app.AppCompatActivity;
  7. import android.support.v7.widget.Toolbar;
  8. import android.text.TextUtils;
  9. import android.view.MotionEvent;
  10. import android.view.View;
  11. import android.webkit.WebChromeClient;
  12. import android.webkit.WebView;
  13. import android.webkit.WebViewClient;
  14. import android.widget.ImageView;
  15. import android.widget.ProgressBar;
  16. import com.bumptech.glide.Glide;
  17. import com.bumptech.glide.load.engine.DiskCacheStrategy;
  18. public class MainActivity extends AppCompatActivity {
  19. private String postUrl = "/members/ganeshan-n";
  20. private WebView webView;
  21. private ProgressBar progressBar;
  22. private float m_downX;
  23. private ImageView imgHeader;
  24. @Override
  25. protected void onCreate(Bundle savedInstanceState) {
  26. super.onCreate(savedInstanceState);
  27. setContentView(R.layout.activity_main);
  28. Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
  29. setSupportActionBar(toolbar);
  30. getSupportActionBar().setDisplayHomeAsUpEnabled(true);
  31. webView = (WebView) findViewById(R.id.webView);
  32. progressBar = (ProgressBar) findViewById(R.id.progressBar);
  33. imgHeader = (ImageView) findViewById(R.id.backdrop);
  34. if (!TextUtils.isEmpty(getIntent().getStringExtra("postUrl"))) {
  35. postUrl = getIntent().getStringExtra("postUrl");
  36. }
  37. initWebView();
  38. initCollapsingToolbar();
  39. renderPost();
  40. }
  41. private void initWebView() {
  42. webView.setWebChromeClient(new MyWebChromeClient(this));
  43. webView.setWebViewClient(new WebViewClient() {
  44. @Override
  45. public boolean shouldOverrideUrlLoading(WebView view, String url) {
  46. if (Utils.isSameDomain(postUrl, url)) {
  47. Intent intent = new Intent(MainActivity.this, MainActivity.class);
  48. intent.putExtra("postUrl", url);
  49. startActivity(intent);
  50. } else {
  51. // launch in-app browser i.e BrowserActivity
  52. openInAppBrowser(url);
  53. }
  54. return true;
  55. }
  56. @Override
  57. public void onPageFinished(WebView view, String url) {
  58. super.onPageFinished(view, url);
  59. progressBar.setVisibility(View.GONE);
  60. }
  61. });
  62. webView.clearCache(true);
  63. webView.clearHistory();
  64. webView.getSettings().setJavaScriptEnabled(true);
  65. webView.setHorizontalScrollBarEnabled(false);
  66. webView.setOnTouchListener(new View.OnTouchListener() {
  67. public boolean onTouch(View v, MotionEvent event) {
  68. if (event.getPointerCount() > 1) {
  69. //Multi touch detected
  70. return true;
  71. }
  72. switch (event.getAction()) {
  73. case MotionEvent.ACTION_DOWN: {
  74. // save the x
  75. m_downX = event.getX();
  76. }
  77. break;
  78. case MotionEvent.ACTION_MOVE:
  79. case MotionEvent.ACTION_CANCEL:
  80. case MotionEvent.ACTION_UP: {
  81. // set x so that it doesn't move
  82. event.setLocation(m_downX, event.getY());
  83. }
  84. break;
  85. }
  86. return false;
  87. }
  88. });
  89. }
  90. private void renderPost() {
  91. webView.loadUrl(postUrl);
  92. }
  93. private void openInAppBrowser(String url) {
  94. Intent intent = new Intent(MainActivity.this, BrowserActivity.class);
  95. intent.putExtra("url", url);
  96. startActivity(intent);
  97. }
  98. private void initCollapsingToolbar() {
  99. final CollapsingToolbarLayout collapsingToolbar =
  100. (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
  101. collapsingToolbar.setTitle(" ");
  102. AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appbar);
  103. appBarLayout.setExpanded(true);
  104. // hiding & showing the txtPostTitle when toolbar expanded & collapsed
  105. appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
  106. boolean isShow = false;
  107. int scrollRange = -1;
  108. @Override
  109. public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
  110. if (scrollRange == -1) {
  111. scrollRange = appBarLayout.getTotalScrollRange();
  112. }
  113. if (scrollRange + verticalOffset == 0) {
  114. collapsingToolbar.setTitle("Web View");
  115. isShow = true;
  116. } else if (isShow) {
  117. collapsingToolbar.setTitle(" ");
  118. isShow = false;
  119. }
  120. }
  121. });
  122. // loading toolbar header image
  123. Glide.with(getApplicationContext()).load("http://www.ourlonelyuniverse.com/wp-content/uploads/2016/01/google-dont-be-evil.png")
  124. .thumbnail(0.5f)
  125. .crossFade()
  126. .diskCacheStrategy(DiskCacheStrategy.ALL)
  127. .into(imgHeader);
  128. }
  129. private class MyWebChromeClient extends WebChromeClient {
  130. Context context;
  131. public MyWebChromeClient(Context context) {
  132. super();
  133. this.context = context;
  134. }
  135. }
  136. }
Step 10
Create a 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 Android. Do not replace your package name, otherwise, the app will not run.
BrowserActivity.java code
  1. import android.content.Context;
  2. import android.graphics.Bitmap;
  3. import android.os.Bundle;
  4. import android.support.design.widget.CoordinatorLayout;
  5. import android.support.design.widget.Snackbar;
  6. import android.support.v7.app.AppCompatActivity;
  7. import android.support.v7.widget.Toolbar;
  8. import android.text.TextUtils;
  9. import android.view.Menu;
  10. import android.view.MenuItem;
  11. import android.view.MotionEvent;
  12. import android.view.View;
  13. import android.webkit.WebChromeClient;
  14. import android.webkit.WebResourceError;
  15. import android.webkit.WebResourceRequest;
  16. import android.webkit.WebView;
  17. import android.webkit.WebViewClient;
  18. import android.widget.ProgressBar;
  19. public class BrowserActivity extends AppCompatActivity {
  20. private String url;
  21. private WebView webView;
  22. private ProgressBar progressBar;
  23. private float m_downX;
  24. CoordinatorLayout coordinatorLayout;
  25. @Override
  26. protected void onCreate(Bundle savedInstanceState) {
  27. super.onCreate(savedInstanceState);
  28. setContentView(R.layout.activity_browser);
  29. Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
  30. setSupportActionBar(toolbar);
  31. getSupportActionBar().setDisplayHomeAsUpEnabled(true);
  32. getSupportActionBar().setTitle("");
  33. url = getIntent().getStringExtra("url");
  34. // if no url is passed, close the activity
  35. if (TextUtils.isEmpty(url)) {
  36. finish();
  37. }
  38. webView = (WebView) findViewById(R.id.webView);
  39. progressBar = (ProgressBar) findViewById(R.id.progressBar);
  40. coordinatorLayout = (CoordinatorLayout) findViewById(R.id.main_content);
  41. initWebView();
  42. webView.loadUrl(url);
  43. }
  44. private void initWebView() {
  45. webView.setWebChromeClient(new MyWebChromeClient(this));
  46. webView.setWebViewClient(new WebViewClient() {
  47. @Override
  48. public void onPageStarted(WebView view, String url, Bitmap favicon) {
  49. super.onPageStarted(view, url, favicon);
  50. progressBar.setVisibility(View.VISIBLE);
  51. invalidateOptionsMenu();
  52. }
  53. @Override
  54. public boolean shouldOverrideUrlLoading(WebView view, String url) {
  55. webView.loadUrl(url);
  56. return true;
  57. }
  58. @Override
  59. public void onPageFinished(WebView view, String url) {
  60. super.onPageFinished(view, url);
  61. progressBar.setVisibility(View.GONE);
  62. invalidateOptionsMenu();
  63. }
  64. @Override
  65. public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
  66. super.onReceivedError(view, request, error);
  67. progressBar.setVisibility(View.GONE);
  68. invalidateOptionsMenu();
  69. }
  70. });
  71. webView.clearCache(true);
  72. webView.clearHistory();
  73. webView.getSettings().setJavaScriptEnabled(true);
  74. webView.setHorizontalScrollBarEnabled(false);
  75. webView.setOnTouchListener(new View.OnTouchListener() {
  76. public boolean onTouch(View v, MotionEvent event) {
  77. if (event.getPointerCount() > 1) {
  78. //Multi touch detected
  79. return true;
  80. }
  81. switch (event.getAction()) {
  82. case MotionEvent.ACTION_DOWN: {
  83. // save the x
  84. m_downX = event.getX();
  85. }
  86. break;
  87. case MotionEvent.ACTION_MOVE:
  88. case MotionEvent.ACTION_CANCEL:
  89. case MotionEvent.ACTION_UP: {
  90. // set x so that it doesn't move
  91. event.setLocation(m_downX, event.getY());
  92. }
  93. break;
  94. }
  95. return false;
  96. }
  97. });
  98. }
  99. @Override
  100. public boolean onCreateOptionsMenu(Menu menu) {
  101. // Inflate the menu; this adds items to the action bar if it is present.
  102. getMenuInflater().inflate(R.menu.browser, menu);
  103. if (Utils.isBookmarked(this, webView.getUrl())) {
  104. // change icon color
  105. Utils.tintMenuIcon(getApplicationContext(), menu.getItem(0), R.color.colorAccent);
  106. } else {
  107. Utils.tintMenuIcon(getApplicationContext(), menu.getItem(0), android.R.color.white);
  108. }
  109. return true;
  110. }
  111. @Override
  112. public boolean onPrepareOptionsMenu(Menu menu) {
  113. if (!webView.canGoBack()) {
  114. menu.getItem(1).setEnabled(false);
  115. menu.getItem(1).getIcon().setAlpha(130);
  116. } else {
  117. menu.getItem(1).setEnabled(true);
  118. menu.getItem(1).getIcon().setAlpha(255);
  119. }
  120. if (!webView.canGoForward()) {
  121. menu.getItem(2).setEnabled(false);
  122. menu.getItem(2).getIcon().setAlpha(130);
  123. } else {
  124. menu.getItem(2).setEnabled(true);
  125. menu.getItem(2).getIcon().setAlpha(255);
  126. }
  127. return true;
  128. }
  129. @Override
  130. public boolean onOptionsItemSelected(MenuItem item) {
  131. if (item.getItemId() == android.R.id.home) {
  132. finish();
  133. }
  134. if (item.getItemId() == R.id.action_bookmark) {
  135. // bookmark / unbookmark the url
  136. Utils.bookmarkUrl(this, webView.getUrl());
  137. String msg = Utils.isBookmarked(this, webView.getUrl()) ?
  138. webView.getTitle() + "is Bookmarked!" :
  139. webView.getTitle() + " removed!";
  140. Snackbar snackbar = Snackbar
  141. .make(coordinatorLayout, msg, Snackbar.LENGTH_LONG);
  142. snackbar.show();
  143. invalidateOptionsMenu();
  144. }
  145. if (item.getItemId() == R.id.action_back) {
  146. back();
  147. }
  148. if (item.getItemId() == R.id.action_forward) {
  149. forward();
  150. }
  151. return super.onOptionsItemSelected(item);
  152. }
  153. private void back() {
  154. if (webView.canGoBack()) {
  155. webView.goBack();
  156. }
  157. }
  158. private void forward() {
  159. if (webView.canGoForward()) {
  160. webView.goForward();
  161. }
  162. }
  163. private class MyWebChromeClient extends WebChromeClient {
  164. Context context;
  165. public MyWebChromeClient(Context context) {
  166. super();
  167. this.context = context;
  168. }
  169. }
  170. }
Step 11
Create a 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 Android. Do not replace your package name, otherwise, the app will not run.
Utils.java code
  1. import android.content.Context;
  2. import android.content.SharedPreferences;
  3. import android.graphics.PorterDuff;
  4. import android.graphics.drawable.Drawable;
  5. import android.support.v4.content.ContextCompat;
  6. import android.view.MenuItem;
  7. public class Utils {
  8. public static boolean isSameDomain(String url, String url1) {
  9. return getRootDomainUrl(url.toLowerCase()).equals(getRootDomainUrl(url1.toLowerCase()));
  10. }
  11. private static String getRootDomainUrl(String url) {
  12. String[] domainKeys = url.split("/")[2].split("\\.");
  13. int length = domainKeys.length;
  14. int dummy = domainKeys[0].equals("www") ? 1 : 0;
  15. if (length - dummy == 2)
  16. return domainKeys[length - 2] + "." + domainKeys[length - 1];
  17. else {
  18. if (domainKeys[length - 1].length() == 2) {
  19. return domainKeys[length - 3] + "." + domainKeys[length - 2] + "." + domainKeys[length - 1];
  20. } else {
  21. return domainKeys[length - 2] + "." + domainKeys[length - 1];
  22. }
  23. }
  24. }
  25. public static void tintMenuIcon(Context context, MenuItem item, int color) {
  26. Drawable drawable = item.getIcon();
  27. if (drawable != null) {
  28. // If we don't mutate the drawable, then all drawable's with this id will have a color
  29. // filter applied to it.
  30. drawable.mutate();
  31. drawable.setColorFilter(ContextCompat.getColor(context, color), PorterDuff.Mode.SRC_ATOP);
  32. }
  33. }
  34. public static void bookmarkUrl(Context context, String url) {
  35. SharedPreferences pref = context.getSharedPreferences("androidhive", 0); // 0 - for private mode
  36. SharedPreferences.Editor editor = pref.edit();
  37. // if url is already bookmarked, unbookmark it
  38. if (pref.getBoolean(url, false)) {
  39. editor.putBoolean(url, false);
  40. } else {
  41. editor.putBoolean(url, true);
  42. }
  43. editor.commit();
  44. }
  45. public static boolean isBookmarked(Context context, String url) {
  46. SharedPreferences pref = context.getSharedPreferences("androidhive", 0);
  47. return pref.getBoolean(url, false);
  48. }
  49. }
Step 12
As we need to make network requests, we need to add internet permission in AndroidManifest.xml. Add the code given below in an AndroidManifest.xml.
AndroidManifest.xml code
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="info.androidhive.webview" >
  4. <uses-permission android:name="android.permission.INTERNET"/>
  5. <application
  6. android:allowBackup="true"
  7. android:icon="@mipmap/ic_launcher"
  8. android:label="@string/app_name"
  9. android:supportsRtl="true"
  10. android:theme="@style/AppTheme.NoActionBar" >
  11. <activity android:name=".MainActivity" >
  12. <intent-filter>
  13. <action android:name="android.intent.action.MAIN" />
  14. <category android:name="android.intent.category.LAUNCHER" />
  15. </intent-filter>
  16. </activity>
  17. <activity android:name=".BrowserActivity"
  18. android:theme="@style/AppTheme.NoActionBar"></activity>
  19. </application>
  20. </manifest>
Step 13
This is our user interface of the Application. Click Make project option.
Android
Step 14
Run the Application, followed by choosing a virtual machine. Click OK.
Android
Deliverables
“Google-Don’t be evil” image is the default. If you want to replace the image, I will change the image link.
Android
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.
Android
Just scroll up the page.
Android
Android
Android
Don’t forget to like and follow me. If you have any doubts, just comment below.
Source code
https://github.com/GaneshanNT/WebView