- TextView
- Программная установка текста
- Атрибуты
- Программная установка фона
- Реагируем на событие onClick
- Многострочный текст
- Увеличиваем интервалы между строками
- Бой с тенью
- Создание ссылок автоматом
- Совет: Используйте полупрозрачность с умом
- Выделить текст для копирования
- What’s your text’s appearance?
- Understanding how to declaratively style text on Android.
- Show some style
- TextAppearance
- Sensible defaults
- Theme
TextView
Компонент TextView предназначен для отображения текста без возможности редактирования его пользователем, что видно из его названия (Text — текст, view — просмотр).
Находится в разделе Texts.
TextView — один из самых используемых компонентов. С его помощью пользователю удобнее ориентироваться в программе. По сути, это как таблички: Руками не трогать, По газону не ходить, Вход с собаками воспрещен, Часы работы с 9.00 до 18.00 и т.д., и служит для представления пользователю описательного текста.
Для отображения текста в TextView в файле разметки используется атрибут android:text, например:
Такой подход является нежелательным. Рекомендуется всегда использовать текстовые ресурсы. В будущем эта привычка позволит вам обеспечить многоязыковую поддержку:
Программная установка текста
Программно текст можно задать методом setText():
Атрибуты
Для всех вышеперечисленных атрибутов в классе TextView есть соответствующие методы для чтения или задания соответствующих свойств.
Программно установим размеры текста при помощи setTextSize() с различными единицами измерения.
По умолчанию у компонентов TextView отсутствует фоновый цвет. Чтобы задать цвет, укажите значение Drawable для атрибута android:background. В качестве значения Drawable может использоваться изображение или XML-представление фигуры, включающий ресурс Drawable (поместить в папку res/drawable).
Программная установка фона
В некоторых случаях программисты из-за невнимательности неправильно меняют фон элемента программным способом и удивляются, почему ничего не работает.
Предположим, у вас определён в ресурсах зелёный цвет:
Следующий код будет ошибочным:
Нужно так (два варианта):
Реагируем на событие onClick
Если вы хотите, чтобы TextView обрабатывал нажатия (атрибут android:onClick), то не забывайте также использовать в связке атрибут android:clickable=»true». Иначе работать не будет!
Многострочный текст
Если вы хотите создать многострочный текст в TextView, то используйте символы \n для переноса строк.
Например, в ресурсах:
Обратите внимание, что в тексте также применяется простое форматирование.
Также перенос на новую строку можно задать в коде:
Увеличиваем интервалы между строками
Вы можете управлять интервалом между соседними строчками текста через атрибут android:lineSpacingMultiplier, который является множителем. Установите дробное значение меньше единицы, чтобы сократить интервал или больше единицы, чтобы увеличить интервал между строками.
Бой с тенью
Чтобы оживить текст, можно дополнительно задействовать атрибуты для создания эффектов тени: shadowColor, shadowDx, shadowDy и shadowRadius. С их помощью вы можете установить цвет тени и ее смещение. Во время установки значений вы не увидите изменений, необходимо запустить пример в эмуляторе или на устройстве. В следующем примере я создал тень красного цвета со смещением в 2 пикселя по вертикали и горизонтали. Учтите, что для смещения используются единицы px (пиксели), единицы dp не поддерживаются.
Программный эквивалент — метод public void setShadowLayer (float radius, float dx, float dy, int color):
Создание ссылок автоматом
У TextView есть ещё два интересных свойства Auto link (атрибут autoLink) и Links clickable (атрибут linksClickable), которые позволяют автоматически создавать ссылки из текста.
Выглядит это следующим образом. Предположим, мы присвоим элементу TextView текст Мой сайт: developer.alexanderklimov.ru и применим к нему указанные свойства.
При этом уже на этапе разработки вы увидите, что строка адреса сайта после слов Мой адрес: стала ссылкой. Если вы запустите приложение и нажмете на ссылку, то откроется браузер с указанным адресом. Вам даже не придется писать дополнительный код. Аналогично, если указать номер телефона (параметр phone), то запустится звонилка.
У ссылки есть интересная особенность — при длительном нажатии на ссылку появляется диалоговое окно, позволяющее скопировать ссылку в буфер обмена.
Атрибут autoLink позволяет комбинировать различные виды ссылок для автоматического распознавания: веб-адрес, email, номер телефона.
Цвет ссылки можно поменять через свойство Text color link (XML-атрибут textColorLink), а программно через метод setTextLinkColor().
Программно можно установить ссылки на текст через класс Linkify:
Кроме константы ALL, можно также использовать Linkify.EMAIL_ADDRESSES, Linkify.MAP_ADDRESSES, Linkify.PHONE_NUMBERS. К сожалению, русские адреса не распознаются. В моём случае индекс был распознан как телефонный номер, а город и улица не стали ссылкой.
В таких случаях придётся самостоятельно добавить ссылки в текстах. Например, определим ссылку в ресурсе:
Присвоим созданный ресурс тексту в TextView и запустим пример. Сам текст будет выглядеть как ссылка, но реагировать не будет. Чтобы исправить данную проблему, добавим код:
Ссылки в тексте выглядят не совсем удобными. Есть отдельная библиотека, которая улучшает функциональность. Описание проблем и ссылка на библиотеку есть в статье A better way to handle links in TextView — Saket Narayan.
Совет: Используйте полупрозрачность с умом
Если вам нужно установить текст полупрозрачным, то не используйте атрибут android:alpha:
Дело в том, что такой подход затрачивает много ресурсов при перерисовке.
Атрибут textColor позволяет установить полупрозрачность без потери производительности:
Выделить текст для копирования
По умолчанию, текст в TextView нельзя выделить для копирования. Но в API 11 появилась такая возможность, которая может пригодиться. Делается либо при помощи XML-атрибута android:textIsSelectable, либо через метод setTextIsSelectable().
Добавьте в разметку два компонента TextView и одно текстовое поле EditText для вставки скопированного текста. У первой текстовой метки установим возможность выделения текста декларативно.
Для второго компонента возможность выделения создадим программно.
Сделайте долгий тап на тексте в любом TextView. Увидите стандартные ползунки для выбора длины текста. Скопируйте текст, сделайте длинный тап в EditText и вставьте текст.
Источник
What’s your text’s appearance?
Understanding how to declaratively style text on Android.
When styling text in Android apps, TextView offers multiple attributes and different ways to apply them. You can set attributes directly in your layout, you can apply a style to a view, or a theme to a layout or perhaps set a text appearance. But which should you use? What happens if you combine them?
This article outlines the different approaches to declaratively styling text (i.e. when you inflate an XML layout), looking at their scope and precedence and when you should use each technique.
You really should read the whole post but here’s a summary.
Be aware of the precedence order of different styling techniques — if you’re trying to style some text and not seeing the results you expect then your changes are likely being overridden by something higher up in this hierarchy:
I’d suggest this workflow for styling text:
- Set any app wide styling in a textViewStyle default style in your theme.
- Set up a (small) selection of TextAppearance s your app will use (or use/extend from MaterialComponent’s styles) and reference these directly from your views
- Create styles setting any attributes not supported by TextAppearance (which themselves specify one of your TextAppearances ).
- Perform any unique styling directly in your layout.
Show some style
While you can directly set TextView attributes in your layout, this approach can be tedious and error prone. Imagine trying to update the color of all text views in your app this way 🙀. As with all views, you can (and should!) instead use styles to promote consistency, reuse and enable easy updates. To this end, I’d recommend creating styles for text whenever you’re likely to want to apply the same styling to multiple views. This is extremely simple and largely handled by the Android view system.
What’s happening under the hood when you set a style on a view? If you’ve ever written a custom view, you’ve likely seen a call to context.obtainStyledAttributes(AttributeSet, int[], int, int) . This is how the Android view system delivers the attributes specified in your layout to the view. The AttributeSet parameter can essentially be thought of as a map of the XML parameters you specify in your layout. If this AttributeSet specifies a style then the style is read first, then the attributes specified directly on the view are applied on top of that. In this way we arrive at our first rule of precedence.
Attributes defined directly on a view always “‘win” and will override those specified in a style. Note that the combination of the style and view attributes are applied; defining an attribute on a view that also appears in the style doesn’t discard the entire style. It’s also interesting to note that there’s no real way in your views to determine where styling is coming from; it’s resolved by the view system for you in this single call. You can’t receive both and pick.
Whilst styles are extremely useful, they do have their limits. One of which is that you can only apply a single style to a view (unlike something like CSS on the web where you can apply multiple classes). TextView however, has a trick up its sleeve, it offers a TextAppearance attribute which functions similarly to a style . If you supply text styling via a TextAppearance that leaves the style attribute free for other styling which sounds useful. Let’s take a closer look at what TextAppearance is and how it works.
TextAppearance
There’s nothing magical about TextAppearance (like a secret mode to apply multiple styles that Android doesn’t want you to know about. 1!), TextView does some very helpful legwork for you. Let’s peek at some of TextView ’s constructor to see what’s going on.
So what is happening here? Essentially TextView first looks if you’ve supplied android:textAppearance , if so it loads that style and applies any properties it specifies. Later on, it then loads all attributes of the view (which remember, includes the style) and applies them. We therefore arrive at our second precedence rule:
Because the text appearance is checked first, any attributes defined either directly on a view or in a style will override the text appearance.
There’s one other caveat to be aware of with TextAppearance which is that is supports a subset of styling attributes that TextView offers. To understand this, let’s go back to this line:
We’ve looked at the 4 arg version of obtainStyledAttributes , this 2 arg version is slightly different. It instead looks at a given style (as identified by the first id parameter) and filters it to only the attributes in this style which appear in the second attrs array param. As such the styleable android.R.styleable.TextAppearance defines the scope of what TextAppearance understands. Looking at the definition of this we can see that TextAppearance supports many but not all attributes that TextView supports.
Styling attributes supported by TextAppearance s
Some common TextView attributes not included are lineHeight[Multiplier|Extra] , lines , breakStrategy & hyphenationFrequency . TextAppearance works at the character level, not paragraph so attributes affecting the whole layout are not supported.
So TextAppearance is very useful, it lets us define a style focused on text styling attributes and leaves a view’s style free for other uses. It does however have a limited scope and is at the bottom of the precedence chain, so be aware of its limitations.
Sensible defaults
When we took a look at how the Android view system resolved attributes ( context.obtainStyledAttributes ) we actually simplified things a little. This calls through to theme.obtainStyledAttributes (using the current Theme of the Context ). Checking the reference this shows the precedence order we looked at before and specifies 2 more places it looks to resolve attributes: the view’s default style and the theme.
We’ll come back to the theme but let’s take a look at default styles. What the heck is a default style? To answer this I think it’s illustrative to take a quick detour from TextView and look at the humble Button . When you drop a into your layout, it looks something like this.
Why? If you look at the source code to Button , it’s pretty sparse:
That’s it! The entire class (less comments). You can check here. I’ll wait. So where does the background, the capitalized text, the ripple etc all come from? You might have missed it, but it’s all in the 2 arg constructor; the one called when a layout is inflated from XML. It’s the last param which specifies a defaultStyleAttr of com.android.internal.R.attr.buttonStyle . This is the default style which is essentially a point of indirection allowing you to specify a, well, style to use by default. It doesn’t directly point to a style, but lets you point to one in your theme which it will check when resolving attributes. And that’s exactly what all themes you’d typically inherit from do to provide the default look and feel for common widgets. Looking at the Material theme for example, it defines @style/Widget.Material.Light.Button and it is this style which supplies all of the attributes, which theme.obtainStyledAttributes will deliver if you don’t specify anything else.
Going back to TextView , it also offers a default style: textViewStyle . This can be very handy if you want to apply some styling to each and every TextView in your app. Say you wanted to set a default line spacing multiplier of 1.2 throughout. You could do this through style s/ TextAppearance s and try to enforce this through code review (or perhaps even a fancy custom Lint rule) but you’d have to be vigilant and be sure to onboard new team members and be careful with refactors etc.
A better approach might be to specify your own default style for all TextView s in the app, encoding the desired behavior. You can do this by setting your own style for textViewStyle which extends from the platform or MaterialComponents/AppCompat default.
So factoring this in, our precedence rules become:
View > Style > Default Style > TextAppearance
As part of the view systems attribute resolution, this slots in after styles (so anything in a default style is trumped by an applied style or view attribute) but still will override a text appearance. Default styles can be pretty handy. If you’re ever writing your own custom view then they can be a powerful way to implement default behavior while allowing easy customization.
If you’re subclassing a widget and not specifying your own default style then be sure to use the parent classes default style in your constructors (don’t just pass 0). For example, if you’re extending AppCompatTextView and write your own 2 arg constructor, be sure to pass android.R.attr.textViewStyle as the defaultStyleAttr (like this) otherwise you’ll lose the parent’s behavior.
Theme
As mentioned before, there’s one (final, I promise) way to provide styling information. The other place theme.obtainStyledAttributes will look is directly in the theme itself. That is if you supply a style attribute like android:textColor in your theme, the view system will pick this up as a last resort. Generally it’s a Bad Idea™ to mix theme attributes and style attributes i.e. something you’d apply directly to a view should generally never be set on a theme (and vice versa) but there are a couple of rare exceptions.
One example might be if you’re trying to change the font throughout your app. You could use one of the techniques above but manually setting up styles/text appearances everywhere would be repetitive and error prone and default styles only work at the widget level; subclasses might override this behavior e.g. buttons define their own android:buttonStyle which wouldn’t pick up your custom android:textViewStyle . Instead you could specify the font in your theme:
Now any view which supports this attribute will pick this up unless overridden by something with higher precedence:
View > Style > Default Style > Theme > TextAppearance
Again, as this is part of the view styling system, it will override anything supplied in a text appearance, but be overridden by any more specific attributes.
Be mindful of this precedence. In our app-wide-font example you might expect Toolbar s to pick up this font as they contain a title which is a TextView . The Toolbar class itself however defines a default style containing a titleTextAppearance which itself specifies android:fontFamily , and directly sets this on the title TextView , overriding the theme level value. Theme level styling can be useful, but is easily overridden so be sure to check that it’s applied as expected.
Источник