Show html in android

How to show an HTML string in an Android TextView

Filed under “What I learned about Android today,” it turns out that you can display an HTML string in an Android TextView . However, this approach has major limitations, and you’ll probably want to display your HTML in a WebView instead.

Skipping past that issue for a few moments . if you want to try to display an HTML string in a TextView , you need to use the Android Html.fromHtml() method, as shown in this code:

My HTML string

In my example code I’ve defined a String in XML in my res/values/strings.xml file like this:

As shown, if you’re going to put HTML content in a string in an XML file like this, you need to put it inside a CDATA element.

What a TextView looks like

With a layout file defined like this:

and a MainActivity defined like this:

the HTML string displayed in an Android TextView widget looks like this:

As you can see, the TextView does not display some elements properly. In fact, the more HTML you want to use, the more this becomes a problem, because the TextView has very little support for displaying HTML.

Android WebView is better

In fact, the display problems are bad enough that you’re probably better off using a WebView instead of a TextView . If you remove the WebView comments from the code I’ve shown, and comment-out the TextView code, you’ll see that a WebView renders the HTML much better:

Summary

So, while you can render an HTML string in an Android TextView , the question becomes, “Should you do this?” For all but the simplest cases, my guess is that you’ll want to use a WebView instead of a TextView , as demonstrated by this example.

Note: For this example I used a minSdkVersion of 14 and a targetSdkVersion of 21, and the output is shown in a Nexus 5 emulator.

Источник

Show html in android

7. FROM_HTML_SEPARATOR_LINE_BREAK_LIST: This flag is used to indicate that texts inside

    elements will be separated from other texts with one newline character by default.

8. FROM_HTML_SEPARATOR_LINE_BREAK_LIST_ITEM: This flag is used to indicate that texts inside
elements will be separated from other texts with one newline character by default.

9. FROM_HTML_SEPARATOR_LINE_BREAK_PARAGRAPH: This flag is used to indicate that inside

elements will be separated from other texts with one newline character by default.

Example 1 Of Parse HTML File content Using WebView With Example In Android Studio:

Below is the example of HTML in which we parse the HTML file and display the HTML content in our Android WebView. In this example firstly we create a assets folder and store a HTML file in it. After that we create a WebView in our XML file and then get the reference of WebView in our MainActivity and finally with the help of loadUrl() method we display the content in our webView.

Step 1: Create a new project and name it HtmlExample.

Step 2: Open res -> layout -> activity_main.xml (or) main.xml and add following code:

In this step we open an xml file and add the code for displaying a WebView.

Step 3: Now create assets folder in App. You can read here how to create assets folder in Android Studio

Step 4: Now inside assets folder add a HTML file name myfile.html. You can read here how to add local html file in Android Studio. Also inside myfile.html add the below HTML content or add any content in HTML format.

Step 5: Now Open src -> package -> MainActivity.java

In this step we open MainActivity where we add the code to initiate the WebView and then display the HTML content from file stored in assets folder into WebView.

Output:

Now run the App and you will see local content added in HTML file is loaded in Webview.

Example 2 Of HTML In Android Studio Using TextView:

Below is the example of HTML in which we display the HTML content in our Android TextView with the help of fromHtml() method. In this example firstly we create a TextView in our XML file and then get the reference of TextView in our MainActivity and finally with the help of fromHtml() method we set the content in our TextView.

Читайте также:  Настройка двойного нажатия андроид

Step 1: Create a new project and name it HtmlExample.

Step 2: Open res -> layout -> activity_main.xml (or) main.xml and add following code:

In this step we open an xml file and add the code for displaying a TextView.

Step 3: Now Open src -> package -> MainActivity.java

In this step we open MainActivity where we add the code to initiate the TextView and then set the HTML content which is stored in a string variable into TextView using fromHtml() method.

Output:

Now run the App and you will see HTML content is shown in TextView.

Example 3 Of HTML content in WebView With Example in Android Studio:

Below is the example of HTML in which we display the HTML content in our Android WebView. In this example firstly we create a WebView in our XML file and then get the reference of WebView in our MainActivity and finally with the help of loadDataWithBaseURL() method we display the content in our webView.

Step 1: Create a new project and name it HtmlWebViewExample.

Step 2: Open res -> layout -> activity_main.xml (or) main.xml and add following code:

In this step we open an xml file and add the code for displaying a WebView.

Step 3: Now Open src -> package -> MainActivity.java

In this step we open MainActivity where we add the code to initiate the WebView and then display the HTML content which is stored in a string variable into WebView.

Output:

Now run the App and you will see HTML content is displayed using Webview.

Источник

Tek Eye

To display lots of informational text and images in an Android app using HTML is a good choice. This article shows how to use HTML5 in Android using a simple example. The HTML file can be created in the Studio editor, or created outside Studio and then copied into the project. The file is placed into the assets folder. An app with a WebView loads the HTML using the Uniform Resource Identifier (URI) file:///android_asset/file.html , where file.html is the created file.

What is HTML?

HTML stands for HyperText Markup Language and is used to display web pages. Modern HTML is often referred to as HTML5, although the World Wide Web Consortium (W3C), who manage web standards, currently have a HTML specification at version 5.2 (as of December 2017). The WHATWG group prefer to keep a rolling specification of HTML. This HTML Living Standard reflects how HTML is (or should be) implemented in the wide variety of available browsers. HTML can be enhanced by applying CSS (Cascading Style Sheets).

Load HTML Page Saved in Android Project

Although this tutorial will be loading a static HTML file, the WebView can also display dynamic HTML by using JavaScript and the Document Object Model (DOM). The combination of HTML for page elements and structure, CSS for formatting, DOM to access the structure, and JavaScript for manipulation makes the WebView a powerful component for displaying large amounts of text and images in an App.

(This Android HTML loading tutorial assumes that Android Studio is installed, a basic app can be created and run, and the code in this article can be correctly copied into Android Studio. The example code can be changed to meet your own requirements. When entering code in Studio add import statements when prompted by pressing Alt-Enter.)

Create Files for HTML5 in Android App Example

For this tutorial the app is called Show HTML. In Studio a new file is created in the app’s assets directory (src/main/assets in the project). To create an assets folder highlight the app in the Project explorer. Then use the context (normally right-click) or the File menu. Select New then Folder, then Assets Folder. In the New Android Component dialog the Target Source Set is left at main, then click Finish.

With the assets folder selected use the File or context menu to select New and then File. Here the file is called crocodile.html. Enter the required HTML. (To see the basic structure of a HTML document look at the article Hello World in HTML.) In this tutorial the text used is a poem by Lewis Carroll from the book Alice’s Adventures in Wonderland. Any text can be used. The image of a crocodile was from openclipart and is in the Public Domain. Save this crocodile image into the assets directory as crocodile.png. (Note, Android Studio supports drag-and-drop from the file system if it is downloaded to a different location).

Читайте также:  Лучшие шагомеры для android

Here is the full text for this HTML example:

Open the app’s default layout file, here called activity_main.xml, add a WebView. If using the graphical designer ensure it fills most of the screen. Here’s a simple layout that can be used:

With the HTML files and layout ready, only the code to load the files is required. The usual findViewById method is used to get a reference to the WebView. Then the loadUrl method of the WebView is used and passed the name of the HTML file. The name is appended to file:///android_asset/ . Note, it is the singular asset and not the same as the directory, which is plural and called assets. Think of it as you save many assets in the directory but only load one asset to display. Open the Java class file for the activity, here called MainActivity.java. Add these two lines of code to the default generated onCreate method:

Here’s the app in action:

Once advantage of the WebView is that it supports scrolling if the page does not fit in the entire display:

Here is the full Java code from the MainActivity.java used in this tutorial:

For further information on the WebView, for example turning on JavaScript support, see the Android docs.

Acknowledgements

See Also

  • Download the code for this example, available in show-html.zip
  • See the Android Studio example projects to learn Android app programming.
  • For a full list of all the articles in Tek Eye see the full site Index.

Archived Comments

Techapps on August 24, 2015 at 12:37 am said:

Hello, First of all I want to say very thank you for this post I know it is 2 years old post but I cannot found it in my search result and after searching of two weeks I found this great help.

Actually I was looking for something similar but non-tutorial (text-video) to help me out, but your post did.

But I’m still one step far from what I want. I have a complete file with folders of images, js and css etc. which is linked with index.html file.

So, if you can help me out with how to link multiple html, css, javascript, and image files it will be great help.

Thank you so much again!

Author: Daniel S. Fowler Published: 2013-09-03 Updated: 2017-12-23

Do you have a question or comment about this article?

(Alternatively, use the email address at the bottom of the web page.)

↓markdown↓ CMS is fast and simple. Build websites quickly and publish easily. For beginner to expert.

Free Android Projects and Samples:

Источник

Текст с разметкой в android.widget.TextView

Недавно мне понадобилось сделать довольно хитроумный чат в приложении под Android. Помимо собственно информации требовалось передавать пользователям дополнительную функциональность в контексте определенного сообщения: имя автора сообщения по нажатию на него должно вставляться в текстовое поле ответа, а если это сообщение о только что созданном игровом сеансе, пользователи должны иметь возможность присоединиться к игре по клику и так далее. Одним из главных требований была возможность создавать сообщение, содержащее несколько ссылок, что и задало направление исследований.

WebView, обладая нужной функциональностью, был отвергнут по причине тяжести решения: я даже не стал создавать 100 или сколько-нибудь там экземпляров в тестовых целях, по одному на каждое сообщение, поскольку сразу было понятно, что это расточительство нормально работать не будет.

К счастью, самый обычный TextView обладает неожиданно потрясающей функциональностью по разметке текста и может использоваться как в качестве отдельного элемента, так и служить целой страницей, будучи несравненно легковеснее, чем WebView.

Я реализовал весь, необходимый мне функционал и выяснил ещё несколько довольно интересных вещей, столкнувшись с некоторым количеством подводных камней (впрочем, не очень острых). Можно сказать, всё нижеописанное — руководство по созданию достаточно мощной справочной системы в своём приложении практически даром.

Задачи

В данном примере мы создадим приложение с двумя Activity, одна из которых содержит TextView, исполняющий роль браузера, из которого, в частности, можно вызвать вторую Activity, демонстрирующую работу с параметрами вызова. Мы выясним, каким образом можно создавать страницы текста с разметкой и изображениями и связывать их ссылками.

Содержимое страниц берётся из строк в ресурсах приложения, а изображения являются drawable-ресурсами. Небольшие изменения в коде позволят использовать другие расположения.

Создание приложения

Любым удобным нам способом создаём обычное приложение:

Немного пояснений к манифесту. Если с первой Activity всё понятно, вторая (AnotherActivity) содержит некие дополнительные описатели.

android:exported=«false» необходимо для того, чтобы компилятор не выдавал предупреждения о том, что мы забыли что-то прописать в экспортируемом компоненте. На мой взгляд, чисто декоративный момент, но чем меньше жёлтых треугольничков — тем спокойнее.

Раздел intent-filter содержит описатели того, каким образом и при каких обстоятельствах будет происходить запуск Activity.

означает, что можно запустить Activity ссылкой вида activity-run://AnotherActivityHost?params.

Значения action и category необходимы системе для того чтобы обнаружить и запустить Activity.

Читайте также:  Android manifest activity intent filter

Подготовка ресурсов

Строки, содержащие разметку, должны иметь аттрибут formatted со значением false, а содержимое должно передаваться в блоке CDATA, чтобы у компилятора не было претензий к разметке и специальным символам. В данном примере признаком статьи будет префикс article_ в названии строки.

Также замечен странный глюк, проявляющийся в том, что если текст начинается с тега, то заканчивается он этим же тегом. Если у вас в начале статьи ссылка, советую ставить перед ней либо пробел, либо
.

Изображения могут быть формата jpg, png или gif без анимации. Анимированный gif отображается статичной картинкой. Расположение стандартное для ресурсов, для дисплеев разной плотности можно подготовить свой вариант картинки. В данном примере все изображения находятся в drawable-nodpi

Как всё работает

Рассмотрим некоторые части кода подробно.

TextView используемый нами в качестве браузера, требует особой инициализации:

tvContent.setLinksClickable(true); указывает на то, что ссылки в данном элементе реагируют на нажатие.

tvContent.setMovementMethod(new LinkMovementMethod()); назначает способ навигации по элементу. Использованный нами LinkMovementMethod интересен сам по себе и, возможно, заслуживает отдельной статьи. Я лишь скажу, что при необходимости более полного контроля можно создать его наследника, переопределенные методы которого позволят отслеживать все действия со ссылками в элементе.

В данном методе происходит получение строки по идентификатору из строковых ресурсов, её преобразование из HTML в специальный объект Spanned, затем ещё одно преобразование в Spannable и установка в TextView в качестве содержимого. Всё это кажется довольно громоздким, но тому есть причины.

В TextView, на мой взгляд, странный порядок обработки спанов — с конца списка. При естественном расположении спанов после преобразования строки из HTML, изменения внешнего вида вложенных спанов перекрываются свойствами спанов, их содержащих. Для нормального отображения приходится буквально выворачивать маркировку наизнанку с помощью метода revertSpanned:

Определение обработчика ссылок на изображения минималистично и призвано загружать только картинки из ресурсов. Поскольку мы рассматриваем вариант справочной системы, я посчитал, что этого будет достаточно. С вашего позволения, я не буду цитировать его. Если вы хотите большего, можно обратиться, например, к данной статье.

Более интересен нам будет Html.TagHadler:

Здесь у нас происходит несколько интересных вещей.

При преобразовании из HTML в Spanned методом Html.fromHtml, обрабатываются тэги br , p , div , em , b , strong , cite , dfn , i , big , small , font , blockquote , tt , a , u , sup , sub , h1. h6 и img . В случае, если тэг не опознан, вызывается Html.TagHandler (если, конечно, он передан в вызов).

Мы проверяем, не является ли переданный тэг «нашим» и если это так, создаём соответствующий Span — элемент разметки, а затем накладываем его на текст. Я создал несколько собственных Span-ов, они будут рассмотрены далее. Как правило, Span-ы наследуются от android.text.style.CharacterStyle.

К сожалению, у меня не получилось малой кровью добиться центрования отдельных строк или абзацев, а встроенной возможности для этого не существует. Также, нельзя прочесть атрибуты тэга из xmlReader, поскольку он реализован не полностью. По этой причине пришлось изобретать свой способ передачи параметров: значение является частью тега. В нашем примере таким образом передаётся значение цвета в тэге color, преобразовываемом в ParameterizedSpan. Получается что-то вроде красный . Это достаточно ограниченный и не очень удобный способ, но иногда лучше такой, чем никакого.

Этот код делает следующее: В случае, если передан открывающий Span, он добавляется к концу строки в текущем её виде. В случае, если Span закрывающий, мы находим в строке его открывающий аналог, запоминаем его положение, затем удаляем и добавляем новый, но уже с информацией о начальном положении и длине.

Мы завершили рассмотрение класса Activity, являющегося основным модулем нашего приложения. Теперь рассмотрим вспомогательные классы.

Это Span общего назначения и с его помощью можно задать большинство параметров стиля текста. Его можно использовать как базу для создания стилей текста из собственных тэгов.

Этот класс описывает элемент, который по нажатию на него обеспечивает переход к статье, чей идентификатор является его параметром. Здесь я применил производное от способа, описанного мной ранее: сам тэг является собственным параметром, а его класс определяется префиксом article_. Поднимемся выше, к описанию Html.TagHandler:

Обработчик тэгов, увидев тэг, начинающийся на article_, создаёт ArticleSpan, задавая ему в качестве параметра название тэга. Элемент, при нажатии на него, вызывает метод MainActivity.setArticle, после чего в TextView устанавливается новый текст.

Здесь реализован элемент, получающий параметр явно и отдельно от своего имени. Претензия на своего рода стандарт именования тэгов, раз уж нельзя передавать атрибуты.

Конечно, всё описанное является вариациями одного принципа, каждый выберёт то, что ему удобнее.

Вызов Activity

В HTML мы видим следующее:

При нажатии на ссылку, происходит вызов AnotherActivity с передачей параметров в Intent. Эти параметры можно получить и использовать:

Использованные материалы

Следующие материалы очень ускорили создание данной статьи, да и, чего уж там, сделали его вообще возможным:

Я очень рад, что существует на свете StackOverflow.com.

Архив с исходниками проекта

Архив с исходными текстами и ресурсами проекта можно взять здесь.

Источник

Оцените статью