WebView
WebView — это компонент, который позволяет встраивать веб-страницы в приложения, своеобразный мини-браузер. Находится в разделе Containers.
В старых версиях Android WebView использовал движок WebKit. В Android 4.4 он стал использовать движок Chromium или Blink. В Android 5 появилось отдельное приложение System WebView, которое можно скачать из Play Market. Такое разделение позволило обновлять движок без обновления системы. На этом приключения не закончились. В Android 7.0 уже используется движок Chrome, а если этого браузера на устройстве нет, то используется System WebView. Подобные выкрутасы не прошли даром, программисты часто жалуются, что какой-то кусок кода не работает. Приходится проверять работу на разных устройствах.
Надеюсь, вы уже познакомились с базовым примером по созданию собственного браузера. Рассмотрим дополнительные возможности элемента WebView.
Загружаем локальные страницы и картинки
Если вы хотите загружать в WebView страницы не из интернета, а со своего приложения, то разместите нужные файлы в папке assets, например, assets/mypage.html. Доступ к файлу вы можете получить через конструкцию file://android_asset:
webView = findViewById(R.id.mybrowser); webView.loadUrl("file:///android_asset/mypage.html");
Аналогично поступаем с картинками, которые встречаются в html-файле
Также можно загрузить файл из папки res/raw:
webView.loadUrl("file:///android_res/raw/cat.html");
Если картинка находится на внешнем накопителе, то попробуйте вариант:
WebView webView = findViewById(R.id.webView); String imageName = "cutecat.png"; String catUrl = "file://" + Environment.getExternalStorageDirectory().getAbsolutePath() .toString() + "/" + imageName; webView.loadUrl(catUrl);
Недавно наткнулся на фрагмент кода, где нужно добавить несколько новых настроек для работы с файлами. Пример для Kotlin.
val webView = findViewById(R.id.webView) // Enable the WebView to access content through file: URLs webView.settings.apply
Загружаем данные при помощи loadData() и loadDataWithBaseURL()
Данные можно загрузить с помощью метода loadData():
String htmlText = "Percent test: 100% "; WebView webView = findViewById(R.id.webView); webView.loadData(htmlText, "text/html", "en_US");
Если текст простой, то этот способ подойдёт. Но в данном примере встречается символ процента, который относится к спецсимволам и часть текста может оказаться недоступной. Если в тексте встречаются подобные символы, то лучше использовать метод loadDataWithBaseURL():
webView.loadDataWithBaseURL(null, htmlText, "text/html", "en_US", null);
Если вам приходится использовать loadData(), то спецсимволы можно заменить при помощи метода replace():
String webData = stringBuffer.toString(); // поступающие данные webData = webData.replace("#", "%23"); webData = webData.replace("%", "%25"); webData = webData.replace("\\", "%27"); webData = webData.replace("?", "%3f"); webView.loadData(webData, "text/html", "UTF-8");
Проблемы с кодировкой
У меня есть программа в Google Play, использующая WebView. К моему удивлению, некоторые пользователи жаловались, что текст нечитаем, так как они видят только кракозябры. Особенно много жалоб было от пользователей с планшетами. Оказалось, что проблема довольна распространённая и обсуждается на форумах. Танцы с бубнами (установка явной кодировки UTF-8) не помогают. Нашёл один ответ, который у некоторых заработал, на всякий случай я его здесь оставлю.
// перед загрузкой данных (load. ) WebSettings settings = mWebView.getSettings(); settings.setDefaultTextEncodingName("utf-8");
Но я рекомендую просто использовать метод loadDataWithBaseURL(). Работает стабильно.
Методы
У WebView есть множество методов, которые позволяют добиваться полной функциональности как у обычного браузера — обновить страницу, перейти на предыдущую страницу и т.д. Часть методов представлена ниже:
- reload()
- goForward()
- goBack()
Используем зум для просмотра
Не забывайте, что WebView можно использовать не только для просмотра html-страниц, но и для просмотра изображений. Поэтому данный компонент вполне можно использовать просмотра картинок с котиками, к тому же вы можете включить встроенный механизм масштабирования:
При работе с протоколом http используйте совет Cleartext HTTP traffic not permitted (https)
mWebView = findViewById(R.id.webView1); // устанавливаем Zoom control mWebView.getSettings().setBuiltInZoomControls(true); // загружаем картинку (не забудьте установить разрешение на интернет) mWebView.loadUrl("http://netsources.narod.ru/friday/alkocat.jpg"); this.setTitle("WebView");

Прозрачность
Устанавливать прозрачность лучше программно. Встречал жалобы, что через XML это свойство не работает.
webView.setBackgroundColor(0x00000000);
WebView в Lollipop
В Android 5.0 компонент доступен в Google Play (Android System WebView) и его можно обновлять на устройстве.
Компонент теперь основывается на движке Chromium и поддерживает следующие новинки.
Можно ознакомиться с некоторыми примерами — GoogleChrome/chromium-webview-samples. Там есть примеры с WebRTC, полноэкранным режимом, касаниями экрана, выбора файла, работой с JavaScript-сценариями.
Кроме того, стал доступен Safe Browsing — механизм, предупреждающий об опасных ссылках. Включается через манифест.
Советы
Фон
Если вы заметили, что экран мерцает во время загрузки WebView, то поменяйте фон. Мерцание происходит из-за смены фона приложения (темы), на белый фон по умолчанию для WebView, а потом на фон, который прописан на странице.
mWebView.setBackgroundColor(Color.parseColor("#3498db")); mWebView.setBackgroundColor(getResources().getColor(R.color.my_color_name)); // и т.п.
Касания экрана
Так как поддерживаются касания экрана, то старайтесь использовать на веб-странице визуальные эффекты нажатия кнопок и других элементов при помощи псевдокласса :active, например, так:
.btn < display: inline-block; position: relative; background-color: #f39c12; padding: 14px; border-radius: 5px; border-bottom-style: solid; border-width: 4px; border-color: #DA8300; >.btn:active
Настройки
В API 24 появилась возможность открыть окно настроек и выбрать движок для WebView:
Intent intent = new Intent(Settings.ACTION_WEBVIEW_SETTINGS); if (intent.resolveActivity(getPackageManager()) != null)
Ночной режим
Появилась поддержка тёмной темы в последних версиях WebView.
implementation "androidx.webkit:webkit:1.2.0-alpha01"
За ночной режим отвечает класс WebViewFeature, который имеет в своём составе коллекцию различных возможностей. Проверить поддержку той или иной возможности можно через isFeatureSupported().
// Поддерживается ли ночной режим if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK))
Всего три варианта для тёмной темы.
- FORCE_DARK_OFF
- FORCE_DARK_AUTO
- FORCE_DARK_ON
Включаем ночной режим.
WebSettingsCompat.setForceDark(webView.settings, WebSettingsCompat.FORCE_DARK_ON)
Получаем текущий режим.
val forceDarkMode = WebSettingsCompat.getForceDark(webView.settings)
Как отслеживать изменения URL адреса в WebView Android?
У WebViewClient есть два события shouldOverrideUrlLoading (старый и новый), есть onPageStarted и onPageFinished. Везде проставил функцию обновления текущего URL. Однако выяснилась проблема, например авито использует в мобильной версии видимо JS загрузку контента или что то другое, и ни одно событие выше указанное не срабатывает.
Как отследить изменения URL в этом случае?
- Вопрос задан более двух лет назад
- 179 просмотров
Android WebView Example Tutorial

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Android WebView is used to display HTML in an android app. We can use android WebView to load HTML page into android app.
Android WebView
Android WebView component is a full-fledged browser implemented as a View subclass to embed it into our android application.
Importance Of Android WebView
For HTML code that is limited in terms of scope, we can implement the static method fromHtml() that belongs to the HTML Utility class for parsing HTML-formatted string and displaying it in a TextView . TextView can render simple formatting like styles (bold, italic, etc.), font faces (serif, sans serif, etc.), colors, links, and so forth. However, when it comes to complex formatting and larger scope in terms of HTML, then TextView fails to handle it well. For example browsing Facebook won’t be possible through a TextView. In such cases, WebView will be the more appropriate widget, as it can handle a much wider range of HTML tags. WebView can also handle CSS and JavaScript, which Html.fromHtml() would simply ignore. WebView can also assist with common browsing metaphors, such as history list of visited URLs to support backwards and forwards navigation. Still WebView comes with its own set of cons such as it’s a much more expensive widget to use, in terms of memory consumption than a TextView. The reason for this increased memory is because WebView is powered by WebKit/Blink that are open source Web rendering engine to power content in browsers like Chrome.
Android WebView Example
Android WebView component is inserted into the XML layout file for the layout we want the WebView to be displayed in. In this example we insert it into the activity_main.xml file as shown below:
Android Studio WebView Code
WebView component is initialized in the MainActivity using its id defined in the activity_main.xml as shown in snippet below:
WebView webView = (WebView) findViewById(R.id.webview);
Android WebView loadUrl
Once we’ve obtained a reference to the WebView we can configure it and load URLs via HTTP. WebView loadUrl() method is used to load the URL into the WebView as shown below:
webView.loadUrl("https://www.journaldev.com");
- Supporting JavaScript: JavaScript is by default turned off in WebView widgets. Hence web pages containing javascript references won’t work properly. To enable java script the following snippet needs to be called on the webview instance:
getSettings().setJavaScriptEnabled(true);
The MainAcivity class below contains all the features discussed till now.
package com.journaldev.webview; import android.app.Activity; import android.os.Bundle; import android.webkit.WebSettings; import android.webkit.WebView; public class MainActivity extends Activity < @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); WebView webView = (WebView) findViewById(R.id.webview); WebSettings webSettings = webView.getSettings(); webSettings.setJavaScriptEnabled(true); webView.loadUrl("https://www.journaldev.com"); >>
Setting the WebViewClient
The default behavior when a user clicks on a link inside the webpage is to open the systems default browser app. This can break the user experience of the app users. To keep page navigation within the WebView and hence within the app, we need to create a subclass of WebViewClient , and override its shouldOverrideUrlLoading(WebView webView, String url) method. Here is how such a WebViewClient subclass would look:
private class MyWebViewClient extends WebViewClient < @Override public boolean shouldOverrideUrlLoading(WebView webView, String url) < return false; >>
When the shouldOverrideUrlLoading() method returns false, the URLs passed as parameter to the method is loaded inside the WebView instead of the browser. To distinguish between the URLs that are loaded within the app and browser the following code needs to be added in the shouldOverrideUrlLoading() method:
if(url.indexOf("journaldev.com") > -1 ) return false; return true;
Note: Returning true doesn’t signify that the url opens in the browser app. In fact the url won’t be opened at all. To load the url into the browser an intent needs to fired. The following subclass contains all the configurations we’ve added.
package com.journaldev.webview; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.webkit.WebView; import android.webkit.WebViewClient; public class WebViewClientImpl extends WebViewClient < private Activity activity = null; public WebViewClientImpl(Activity activity) < this.activity = activity; >@Override public boolean shouldOverrideUrlLoading(WebView webView, String url) < if(url.indexOf("journaldev.com") >-1 ) return false; Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); activity.startActivity(intent); return true; > >
The constructor takes Activity as a parameter to fire an intent in the browser. Before instantiating this subclass in the MainActivity lets look at another important feature.
Navigation WebView with Back Button
If we click the back button in the app developed so far we see that the application returns to the home screen even though we’ve navigated through a few pages within the WebView itself. To go through the browsing history on pressing back button we need to modify the back button function as shown in the snippet below:
@Override public boolean onKeyDown(int keyCode, KeyEvent event) < if ((keyCode == KeyEvent.KEYCODE_BACK) && this.webView.canGoBack()) < this.webView.goBack(); return true; >return super.onKeyDown(keyCode, event); >
The onKeyDown() method has been overridden with an implementation that first checks if the WebView can go back. If the user has navigated away from the first page loaded inside the WebView, then the WebView can go back. The WebView maintains a browsing history just like a normal browser. If there is no history then it will result in the default behavior of back button i.e. exiting the app. Following is the code for MainActivity with the above features included.
package com.journaldev.webview; import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import android.webkit.WebSettings; import android.webkit.WebView; public class MainActivity extends Activity < private WebView webView = null; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.webView = (WebView) findViewById(R.id.webview); WebSettings webSettings = webView.getSettings(); webSettings.setJavaScriptEnabled(true); WebViewClientImpl webViewClient = new WebViewClientImpl(this); webView.setWebViewClient(webViewClient); webView.loadUrl("https://www.journaldev.com"); >@Override public boolean onKeyDown(int keyCode, KeyEvent event) < if ((keyCode == KeyEvent.KEYCODE_BACK) && this.webView.canGoBack()) < this.webView.goBack(); return true; >return super.onKeyDown(keyCode, event); > >
Below image shows the output produced by our project, you can see that WebView is loaded with a preassigned url.
Alternatives for Loading Content in the WebView
Till now we’ve just used loadUrl() method to load the contents in the WebView. Here we’ll see the other ways to load content after a quick briefing of the usages of loadUrl(). loadUrl() works with:
- https:// and https://URLs
- file:// URLs pointing to the local filesystem
- file:///android_asset/ URLs pointing to one of your applications assets
- content:// URLs pointing to a ContentProvider that is publishing content available for streaming
Instead of loadUrl() we can use loadData() by which we can display snippets or whole of the HTML code in the method. There are two flavors of loadData(). The simpler one allows us to provide the content, the MIME type, and the encoding, all as strings. Typically, MIME type will be text/html and the encoding will be UTF-8 for ordinary HTML as shown below:
webView.loadData("Hello, world!", "text/html", "UTF-8");
Below is the output when the above snippet is added in the MainActivity as shown below:
package com.journaldev.webview; import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import android.webkit.WebSettings; import android.webkit.WebView; public class MainActivity extends Activity < private WebView webView = null; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.webView = (WebView) findViewById(R.id.webview); WebSettings webSettings = webView.getSettings(); webSettings.setJavaScriptEnabled(true); WebViewClientImpl webViewClient = new WebViewClientImpl(this); webView.setWebViewClient(webViewClient); //webView.loadUrl("https://www.journaldev.com"); webView.loadData("Hello, world!", "text/html", "UTF-8"); > @Override public boolean onKeyDown(int keyCode, KeyEvent event) < if ((keyCode == KeyEvent.KEYCODE_BACK) && this.webView.canGoBack()) < this.webView.goBack(); return true; >return super.onKeyDown(keyCode, event); > >
There is also a loadDataWithBaseURL() method. This takes, among other parameters, the base URL to use when resolving relative URLs in the HTML. Any relative URL (e.g.,
) will be interpreted as being relative to the base URL supplied to loadDataWithBaseURL(). The historyUrl parameter is the URL to write into the WebView internal navigation history for the HTML loaded into the WebView. The following snippet shows a prototype for it:
String baseUrl = "https://www.journaldev.com"; String data = "Relative Link"; String mimeType = "text/html"; String encoding = "UTF-8"; String historyUrl = "https://www.journaldev.com"; webView.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl);
This brings an end to android WebView example tutorial. You can download final android webview project from below link.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Как получить ссылку со страницы в WebView?
Есть страница contentFinal , которая загружается в WebView через фильтры Jsoup . В загруженной странице есть ссылки, ведущие на другие страницы сайта.
WebView cntContent; WebView cntComments; WebSettings webSettingsContent; WebSettings webSettingsComments; cntContent = findViewById(R.id.cntContent); cntComments = findViewById(R.id.cntComments); webSettingsContent = cntContent.getSettings(); webSettingsComments = cntComments.getSettings(); webSettingsContent.setDefaultFontSize(16); webSettingsComments.setDefaultFontSize(16); cntContent.setBackgroundColor(Color.TRANSPARENT); cntComments.setBackgroundColor(Color.TRANSPARENT); webSettingsContent.setAppCacheEnabled(true); webSettingsComments.setAppCacheEnabled(true); cntContent.loadDataWithBaseURL(contentUrl, contentFinal, "text/html", "utf-8", null); cntComments.loadDataWithBaseURL(contentUrl, commentsFinal, "text/html", "utf-8", null); cntContent.setClickable(true);
Как заполучить url ссылки при клике на нее пользователем? И как отследить именно клик на ссылке? Т.е. мне необходимо отследить клик пользователя на ссылку и заключить ее в, например, String userUrl . Далее, я уже переназначу действие.