Android spanned to string

Использование RichText в Android. Spannable

Привет Хабраобщество! Эта статья об использовании Spannable в Android. Предназначен он для стилизации текста. Если Вас интересует как реализовать нечто подобное:

тогда добро пожаловать под кат. Статья ориентированная на разработчиков, у которых нет большого опыта разработки под Android.

Теория

Spannable — интерфейс, который описывает маркировку обычного текста некими объектами. Задание этих объектов заключается в присвоению части текста некоторого определенного стиля. Такими маркировочными объектами могут быть экземпляры классов, которые реализуют интерфейс ParcelableSpan. Добавление маркировки осуществляется методом:

Удаление, соответственно, методом:

Теории немного, перейдем сразу к практике.

Практика

Для освоения практики необходимо создать android проект или открыть уже существующий. Я создал чистый проект, на главную activity разместил один TextView. Идем в метод, где будем инициализировать наш TextView (у меня onCreate) и добавляем следующий текст:

Итак, разберемся что же мы написали. SpannableString — класс, который реализует интерфейс Spannable (с другими реализациями можно ознакомится на сайте официальной документации). UnderlineSpan — реализация ParcelableSpan, маркирует часть текста как подчеркнутый (в нашем примере это с 8-ой по 17-тую букву). Флаг Spanned.SPAN_EXCLUSIVE_EXCLUSIVE обозначает, что наш span не будет расширятся на вставки текста слева или справа от маркированной части. (Со всеми флагами можно ознакомится на официальном сайте, при работе с текстами readonly они не столь важны).

Также здесь ми использовали еще одну реализацию ParcelableSpanStyleSpan. Как вы уже догадались, с его помощью можно маркировать текст как полужирный (Typeface.BOLD) или курсив (Typeface.ITALIC).

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

Хорошо, идем дальше: добавим на наше activity кнопку, а в инициализирующий метод следующий текст:

На этот раз не будем разбирать код, ничего нового уже для нас нет. Мы использовали маркировку курсивом, которую я описал выше. Запускаем, смотрим.

Мы смогли вывести стилизованный текст на кнопку.

Пойдем еще дальше, реализуем обработчик события клика кнопки, в нем пишем следующий код:

Здесь у нас появляется новый класс — ForegroundColorSpan, который задает цвет нашему тексту, в примере мы задали зеленой. Мы его используем в паре с StyleSpan. Запускаем приложение, смотрим на результат.

Мы смогли запихнуть стилизованный текст даже в Toast. Также мы показали, что для одной части текста можно использовать несколько маркировок со стилями.

Вместо заключения

В примере мы использовали только некоторые из доступных стилей, больший список можно посмотреть на сайте разработчиков. Думаю вы сможете поэкспериментировать с ними.

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

Источник

Getting Started with Spannables on Android

Begin formatting text like a pro!

T ext, probably the most basic element you get to work with on Android, and sometimes we have to format certain parts of our text. Formatting helps place emphasis on text, indicating that the formatted parts of text mean more when compared to plain parts. Formatting options include underline, bold, italics, strikethrough and many more. Android provides a number of options to its’ developers when it comes to formatting text. A direct approach is by using HTML markup to define sections of our text to be formatted, tags like the — underline, — bold and — italics do just that. Android properly helps us convert the markup provided into nicely formatted text.

Читайте также:  Edjing pro для андроид

Using XML

Or Code

We have an awesome option for formatting, don’t we? but that’s not all there is to formatting.

Formatting is the arrangement of a material in a particular layout, shape, size and general makeup — Merriam-Webster

Formatting goes beyond boldening or underlining text, we have a pool of design possibilities we can replicate. For example, we might want to set the colour of a fraction of our text differently or its size or its background, whatever. These designs are achievable using spannables without having to worry about too much.

Our First Spannable

To get started, create a new android studio project with your preferred project name and add this to the activity_main.xml . In the code below, we have a parent LinearLayout and five textviews. Android treats spannables like basic text so we can easily set the formatted text to the textviews, hence the usage of textviews.

In the layout above, we created five TextView s to hold differently formatted text, we’d go through them one after the other, starting with the bold format. But before that, let’s take a moment to understand the general structure of how spannables are set up and how the formatting takes place.

How are spannables set up?

When it comes to using Spannables, we can create them in three ways. By using any of the SpannedString, SpannableString and the SpannableStringBuilder classes. Each of these classes has features that differentiate them, the differences are outlined below.

  1. SpannedString — This class does not allow modifications to the text set into the Spannable. No modifications to the text and no modifications to the design (the spans). In other words, it’s immutable.
  2. SpannableString — This class allows for modifications of the design/styles added to the text, but no direct modification of the text used by the Spannable.
  3. SpannableStringBuilder — This class allows for modifications to the text itself and its designs.

The key takeaway here can be summarised as such:

Use SpannedString when you want to set the text and design once without any further modifications, SpannableString when you won’t be making any changes to the text but to the design and SpannableStringBuilder when you’d be making changes to both the underlying text and the design.

Format For Spannables

Now that we have a clear view of the types of spans we can use, let’s dig deeper into their general structure. Spannables you’d use in the future generally come in this fashion:

Our spannable object provides a setSpan method we can use to apply different span styles to sections of our text. It takes in four arguments, let’s dive in!

  1. what — This refers to the actual span style we would be applying, think of it as an object that instructs our spannable to apply a certain style to the text.
  2. startIndex — Remember our spannables deal with text? Right. The startIndex parameter denotes the index where the text to be formatted begins. Say the text to be formatted is thyself in steady thyself , we could deduce that the startIndex for this text is 7.
  3. endIndex — This does pretty much the opposite of what the startIndex does, it denotes the index of the character that ends the text to be formatted. Using our example from our startIndex explanation, our endIndex is the index of the letter f in thyself , so that would make it 13.
  4. flags — This indicates how the text provided to the spannables should be treated, we have various values that can be assigned to this parameter position, examples are SPAN_EXCLUSIVE_EXCLUSIVE , SPAN_EXCLUSIVE_INCLUSIVE , SPAN_INCLUSIVE_INCLUSIVE and many more. A detailed explanation is provided below.
Читайте также:  Utorrent android куда сохраняет файлы

Spannable Flags

As explained above, spannable flags indicate how the Spanning process should treat the text to be spanned. Some of the flags we can use are explained below.

  1. SPAN_INCLUSIVE_INCLUSIVE: This allows new text to be added to both the starting and end points of the text.
  2. SPAN_INCLUSIVE_EXCLUSIVE: This allows new text to be added to the starting point, but not to the end.
  3. SPAN_EXCLUSIVE_INCLUSIVE: This does not allow text to be added to the starting point, but the end.
  4. SPAN_EXCLUSIVE_EXCLUSIVE: This does not allow text to be added to the start and end points of the text.

You can read about other span flags here, since we have covered the general structure of applying spans, and dug deep into it’s required parameters, this seems like a good time to write our first span.

The Bold Span

Let’s start by retrieving a reference to a TextView in our layout, and then setting up a function to apply the spanning. We do that by writing:

Источник

Spannable String: Text Styling with Spans

Text styling is one of the important aspects when it comes to enhancing the UI of an Android application. In Android, we can change the size, color, weight, style, etc of a text and make the text more attractive and appealing.

But think of a situation, when you want different colors for different parts of a TextView. For example, if the text is «Hello Android» and you want to have the color of «Hello» as green and «Android» as red. How can you achieve this? You can make two TextViews and set the textColor to green and red respectively. But it is not a good way of doing this. So, here comes the role of Styling the texts with the help of Spans.

In this blog, we are going to learn how to use Spans for styling our text used in our application. We are going to cover the following topics:

  • What are Spans?
  • Change different colors for different words in a TextView
  • Spannable Flags
  • Change the background color of some part of a TextView
  • Multiple Spans to the same text
  • Different font size of the string in the same TextView
  • Underline a part of the text in TextView
  • Set some part of the TextView Clickable
  • Add a Bulleted list in Android

What are Spans?

Spans are markup objects that are used to style a text either at the character level(for example, changing colors of different words) or at the paragraph level(for example, making a bullet list).

In order to style a text with the help of Spans, you can use the following three classes:

  • SpannedString: This is used when there is no need to modify the text or the markup after its creation.
  • SpannableString: This is used when there is no need to modify the text but you need to modify the markup i.e. you need to add some spans to your text.
  • SpannableStringBuilder: This is used when you need to modify the text as well as the markup.

This is a quick intro about the Spans in Android. Now, let’s see some of the use-cases of it. In all of our example, we are going to use the following TextView having id as tvMessage :

Change different colors for different words in a TextView

There may be situations when you want to have different colors for a different part of the same textview. So, here you can use the ForegroundColorSpan .

Читайте также:  Как правильно обновить смартфон андроид

Here, we are changing the color of «MindOrks» to Red. The output of the above code will be:

If you look at the code, then you will find that we are using the SpannableString class because we are having a fixed text. Also, we are using the setSpan method to set the foreground color of text starting from the 36th position and ending at the 44th position in the string. Also, we are passing some flags with it i.e. the Spannable. SPAN_EXCLUSIVE_INCLUSIVE .

Let’s learn about these flags.

Spannable Flags

There are many flags that can be used with Spans but the most commonly used flags are:

  • SPAN_EXCLUSIVE_EXCLUSIVE
  • SPAN_EXCLUSIVE_INCLUSIVE
  • SPAN_INCLUSIVE_EXCLUSIVE
  • SPAN_INCLUSIVE_INCLUSIVE

These flags are used to tell the Spans whether or not the Span should include the text that is inserted at the start or the end position. Inclusive means add it to the Span and exclusive means remove it from the Span.

If you are using an immutable string i.e. if you are not adding other strings with your original string then all the four flags will work the same. But if you are using a mutable string, then the role of these four flags will come into play. Let’s understand this with the help of an example.

Here, we are going to insert some text in our original string. So, as discussed earlier, for mutable string, we need to use the SpannableStringBuilder .

The corresponding output for all the four flags are shown as below:

Multiple Spans to the same text

You can use the setSpan method as many times as you want on a single text also. For example, if you want to change the color of a text, make it bold and italic at the same time, then you can do this by:

Here, the color of the text is Red and it is bold and italic at the same time. The output of the above code will be:

You can use the setSpan method as many times as you want.

Change the background color of some part of a TextView

You can change the background color of some parts of the text in the TextView by using BackgroundColorSpan .

Here, we are changing the background to Red. The output of the above code will be:

Different font size of the string in the same TextView

You can use RelativeSizeSpan to change the size of some parts of the TextView. The change in the size of the text will be relative i.e. with respect to other text in the string.

Here, the size of «MindOrks» is 2f than other text. The output of the above code will be:

Underline a part of the text in TextView

You can underline a part of the text by using the UnderlineSpan as below:

The output of the above code will be:

Set some part of the TextView Clickable

You can set some parts of the TextView clickable using the ClickableSpan . For example:

Here, on clicking «MindOrks» a toast is displayed. The output of the above code will be:

Add a Bulleted list in Android

With the help of BulletSpan , you can create a bullet list in your application to display some information in a short and simple way.

The output of the above code will be:

So, in this way, we can use Spans to style the texts present in our application.

Hope you learned something new today and I am sure that you are going to use these awesome features in your app very soon.

Do share this blog with other developers to spread the knowledge.

Источник

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