Android settextsize from dimension

400+ Android & Flutter Code

Example code for android + flutter app developers.

Saturday, January 3, 2015

How to change TextView font size in android

TextView widget display text on android application. we can set or change TextView font size statically by declarative syntax in xml layout file or programmatically at run time in java file. even we can use an xml file source to define font size.

the following example code demonstrate us how can we define TextView font size in xml layout file and how can we uses dimens.xml to reference font size. in this example we did not changes any coding in java file, so here we only include the layout xml file and dimens.xml file.

Dimension
we defined dimension value in xml layout file as example 50sp, 20pt, 30dp. dimension is specified with a number followed by a unit of measure. android supported the following units of measure, those are dp, sp, pt, px, mm, in.

dp means Density-independent-Pixels. this is an abstract unit that is based on the physical density of the screen.

sp means Scale-independent-Pixels. SP as like dp but it is also scaled by the user’s font size preference. Sp is recommended unit for measure.

pt means Points — 1/72 of an inch based on the physical size of screen. px describe Pixels which corresponds to actual pixels on the screen. mm is Millimeters which is based on the physical size of the screen. in describe inches which also based on the physical size of the screen.

Источник

How to set text size using dimension from xml at runtime programmatically?

In dimens.xml, I have:

In runtime, I get this value and set the text size of a text view:

On a 10″ tablet (1280 x 800), everything is ok; but on a phone (800 x 480), the text view has a very large font. On the tablet, the size equals 18; on the phone, it’s 27.

If I set the size manually by:

the size is normal on both devices.

Answers

Add dimension in dimens.xml:

Set the size in code:

For setting text size from layout-

For Immediate text display-

In values folder-

As @iDroid Explorer pointed out, posting and accepting the answer can be of help to someone else. Adapting from my reply to Tom’s comment:

I found the solution to my problem. After some attempts I’ve realized that the problem was the android:selectAllOnFocus=»true» line (Read @Tom’s explanation for probabale reason). I just removed that line and now everything is working very well, the text is complete and scrolling like desired when it is too long for the containing view.

Источник

Читайте также:  Блокнот с таблицами для андроид

Making the most of TextView auto-sizing on Android

Dynamically adjusting the size of text on Android with a simple API

TextView auto-sizing was introduced to the framework with Android 8.0 Oreo (API 26). It offers a simple yet powerful API to solve a particular problem: scaling of text size to fit text bounds.

When is this needed? 🤔

For Android Development, using a fixed textSize , layout_width=»match_parent” and layout_height=»wrap_content” (perhaps inside a scrollable parent) is fairly common practice and suitable for most TextView use cases.

However, consider the case where the width and/or height of the text bounds are fixed and the text needs to adapt to the available space. Examples include a newspaper-style layout, a font selector that needs to show each different font typeface/name on a single-line, etc. The text can’t scroll and we can’t just add a «read more» button. In these scenarios, TextView auto-sizing is precisely what we need.

The basics 🔤

The TextView auto-sizing API is fairly concise. It can be implemented in XML layouts or programmatically. There are three distinct ways of enabling auto-sizing on a TextView , with increasing levels of specificity: Default, Granular and Preset.

At the time of this writing, the chances of anyone having a minSdk of 26 are quite slim. Thankfully, all of the auto-sizing functionality is available in the AndroidX core package (formerly Support Library). The differences to the framework API are minimal:

  • Use the app namespace for XML attributes
  • Use the functions in TextViewCompat instead those on TextView directly

Note: All of the examples in this post will use the AndroidX implementation.

Before we get going, there are two important points to keep in mind:

  • Auto-sizing (as the name would suggest) only adjusts the text size. Other properties (eg. letterSpacing , lineHeight , etc.) are not changed. They do, of course, affect the text layout bounds and thus impact the automatic size chosen for the text.
  • It is advised to not use a layout_width or layout_height of «wrap_content» when using TextView auto-sizing, as this may lead to unexpected results. Using a fixed dimension or «match_parent» is fine (or a “0dp” match_constraint if you are using ConstraintLayout ) .

Default auto-sizing 1️⃣

This is the simplest way of enabling TextView auto-sizing. Given the bounds and attributes of a TextView , the text size is adjusted in an attempt to perfectly fit the horizontal and vertical axes.

Note: The granularity dimensions for default auto-sizing are minTextSize = 12sp, maxTextSize = 112sp, and granularity = 1px (see Granular auto-sizing below).

In XML:

Programmatically:

where autoSizeTextType can be:

  • TextViewCompat. AUTO_SIZE_TEXT_TYPE_UNIFORM (enabled)
  • TextViewCompat. AUTO_SIZE_TEXT_TYPE_NONE (disabled)

Granular auto-sizing 2️⃣

This allows you to define the values used in uniform auto-sizing: the minimum and maximum text sizes as well a dimension for the size of each «step». A «step» is the increase/decrease in size of the text layout bounds. The text size scales uniformly between the minimum and maximum text size after each «step».

In XML:

Programmatically:

where unit is the TypedValue dimension unit of all of the configuration values (eg. TypedValue. COMPLEX_UNIT_SP ).

Читайте также:  Гитара для андроид полная версия

Preset auto-sizing 3️⃣

This allows you to specify all the possible values used for auto-sizing. The most appropriate text size will be picked from these values to fit the text bounds.

In XML:

Add the preset sizes to res/values/arrays.xml:

Programmatically:

where unit is the TypedValue dimension unit of the preset size values in the array.

Pro-tips and gotchas 🤓

Mixing value types:

You may have noticed that the programmatic versions of granular and preset auto-sizing could be limiting: the TypedValue unit in these functions applies to all of the supplied auto-sizing values. If you want to mix types (eg. PX and SP) then you need to do so in XML.

Auto-sizing to a single line:

You may be required to restrict auto-sized text to a single line. You can set the lines or maxLines TextView layout attributes to «1» (or use the programmatic equivalent). You may also need to adjust the granular autoSizeMinTextSize , as single-line text will be clipped if the minimum text size is reached but the width still exceeds that of the layout bounds.

Performance:

For performance optimization, one might assume that using preset auto-sizing is the best option. In reality, granular text sizes are precomputed given the minimum, maximum and step values and the difference is negligible.

I hope this post has provided some insight into TextView auto-sizing and how best to make use of it. If you have any questions, thoughts or suggestions then I’d love to hear from you!

Источник

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 и вставьте текст.

Источник

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