- Единицы измерения
- Переводим dp в пиксели
- Настройка шрифтов
- Используем стандартные системные размеры шрифтов
- Android User Interface Design: Basic Font Sizes
- How Users Can Configure Font Settings
- Using Dynamic Font Sizes
- Using Fixed Pixel Sizes
- Using Standard System Font Sizes
- Conclusion
- Making the most of TextView auto-sizing on Android
- Dynamically adjusting the size of text on Android with a simple API
- When is this needed? 🤔
- The basics 🔤
- Default auto-sizing 1️⃣
- In XML:
- Programmatically:
- Granular auto-sizing 2️⃣
- In XML:
- Programmatically:
- Preset auto-sizing 3️⃣
- In XML:
- Programmatically:
- Pro-tips and gotchas 🤓
- Mixing value types:
- Auto-sizing to a single line:
- Performance:
- Designing accessible text for Android: variable font and screen sizes
- Always use “scale-independent pixels” for font measurement
- Design for adjustable font sizes
- Strict height constraints? Limit overflow text.
Единицы измерения
Исторически так сложилось, что разработчики всегда использовали пиксели при создании компьютерных интерфейсов. Но с развитием технологий данный подход стал источником проблем — на многих новых дисплеях элементы стали очень мелкими при установленных высоких разрешениях. Поэтому стали появляться новые единицы измерения, не зависящие от разрешения экрана.
Android поддерживает несколько стандартных единиц измерения. Вкратце перечислим их.
- px (pixels) — пиксели. Точки на экране — минимальные единицы измерения;
- dp (density-independent pixels) — независимые от плотности пиксели. Абстрактная единица измерения, основанная на физической плотности экрана с разрешением 160 dpi. В этом случае 1dp = 1px;
- dip — синоним для dp. Иногда используется в примерах Google;
- sp (scale-independent pixels) — независимые от масштабирования пиксели. Допускают настройку размеров, производимую пользователем. Полезны при работе с шрифтами;
- in (inches) — дюймы, базируются на физических размерах экрана. Можно измерить обычной линейкой;
- mm (millimeters) — миллиметры, базируются на физических размерах экрана. Можно измерить обычной линейкой;
- pt (points) — 1/72 дюйма, базируются на физических размерах экрана;
Как правило, при установке размера текста используются единицы измерения sp, которые наиболее корректно отображают шрифты:
В остальных случаях рекомендуется использовать dp.
Переводим dp в пиксели
Так как на разных устройствах dp может различаться, то для получения величин в пикселях и наоборот используйте методы (float):
Часто точность не требуется и можно использовать целые числа int. Напишем аналогичные методы.
На Kotlin можно написать функцию-расширение:
Если вы не определили размеры в XML, то их можно задать программно с помощью следующего кода (устанавливаем отступы для компонента):
Настройка шрифтов
Давайте чуть подробнее поговорим о работе со шрифтами, чтобы лучше понять специфику работы с текстами. Все люди разные — у кого-то зрение хорошое, у кого-то плохое. Android позволяет в настройках задать размеры шрифта в четырёх вариантах: Мелкий, Обычный, Крупный, Огромный. Для этого нужно зайти в Настройки | Экран | Размер шрифта.
Можно узнать программно выбранный вариант через свойство fontScale:
Обычному шрифту соответствует значение 1, мелкому — 0.9, крупному — 1.1, огромному — 1.15.
Если вы хотите, чтобы ваш текст мог меняться в зависимости от выбора пользователя, то используйте единицы измерения SP:
В тех случаях, когда изменять текст по желанию пользователя не следует, но при этом текст должен отображаться корректно в зависимости от разрешения экрана устройства, то используйте единицы измерения DP.
Третий вариант — если вы ни при каких обстоятельствах (какой же вы упрямый) не хотите зависеть от предпочтений пользователя и разрешения экрана, то пользуйтесь PX (пиксели). Среда разработки будет сопротивляться вашему желанию и выводить предупреждающие сообщения. Подумайте ещё раз о своём решении.
Используем стандартные системные размеры шрифтов
В Android зашиты три системный размера шрифтов, основанных на SP: Small, Medium и Large. Вы можете использовать их в стандартных случаях, когда вам не нужно задавать конкретные значения (атрибут style):
На самом деле стилей @android:style/TextAppearance.* гораздо больше. Если вы вдруг забыли про названия стилей, то можете использовать встроенные возможности среды разработки. На панели инструментов виджет TextView представлен в четырёх вариантах: TextView, Large, Medium, Small, и в них используется атрибут android:textAppearance.
Создадим проект со всеми возможными вариантами и посмотрим на результат. В первом случае будем использовать стандартные настройки шрифта, во втором — увеличим его.
Источник
Android User Interface Design: Basic Font Sizes
Android device screens come in all shapes and sizes. Android developers often include text in their applications that needs to be readable, regardless of what device the application is running on. By using some simple methods, developers can write one application whose text will display reasonably well for all sorts of devices, including supporting the user’s own text size preferences, with little extra work.
In this quick tutorial, we will discuss some of the steps that developers can take to make the text in their applications clear and readable, as well as flexible enough to work on a variety of screen types and across multiple user display settings.
How Users Can Configure Font Settings
Some users have great eyesight and others literally nearly blind. The Android operating system recognizes this fact and provides accessibility features to allow the device text font size to be scaled based on the user’s preference.
To change the font settings on the device, launch the Settings application, then choose Display, Font Size. The user font preference can be set to make text one of four font size settings (Small, Normal, Large, and Huge), as shown in Figure 1.
Using Dynamic Font Sizes
When you want your text to be flexible, based on the user preferences, defne text font sizes using SP (scalable point) units. The Android platform allows dimensional values to be defined in a variety of ways. When it comes to text sizes, you will want to use density-independent units like DP (device-independent pixels) and SP. The SP unit is perfect for text sizes, as it is sensitive to the user’s display settings.
Here’s an example of a TextView that defines its size in terms of SP units:
When it comes to title or heading text, and not text in a free flowing text box, you may not want the user to be able to control the size of the text. In this case, you’d use the DP unit, as it scales in pixels with the density of the device, but not with user settings.
Using Fixed Pixel Sizes
When you don’t want your text to scale no matter what, use absolute pixel sizes with the px unit. There may be some situations when you do not want your text to scale or change size. While this is discouraged, as it may make font sizes unreadable on some devices, here’s how you can do it if you have a good reason for doing so. Simply use one of the absolute units, such as the PX (pixels).
Here’s an example of a TextView that defines its size in terms of PX units. The text displayed by this control will not scale based on the user’s preferences or other factors.
Using Standard System Font Sizes
The Android platform defines a set of relative font size styles that you can use in your applications: Small, Medium, and Large. These font sizes are built upon the SP unit type, so they will scale with user preferences.
The following XML defines three TextView controls, one that will be displayed using the Small font, one in the Medium font, and the third in the Large font size.
Now let’s pull everything together and show you what all these different TextView controls would look like on an Ice Cream Sandwich-style device. In the first figure, the user has a Normal font preference, and in the second figure, the user has a Huge font preference. Note how the TextView controls display under these conditions.
Conclusion
Android devices come in all shapes and sizes and Android users have different needs in terms of application accessibility, such as the need for larger font sizes. Because of the screen limitations, applications that use text need to take some steps to keep typography readable and flexible for different screens. To start, make certain that your application uses scale-independent pixel units (SP), but understand that this font size can change pretty drastically based upon user preferences.
Источник
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!
Источник
Designing accessible text for Android: variable font and screen sizes
When people say that it’s important to build an “accessible” app, that generally means that the app should be usable by as many people as possible, regardless of any disabilities they might have. The most common disabilities that affect mobile applications are vision and motor control impairments. For those with some degree of vision impairment, apps should be designed to allow for variable size fonts and screens, as well as for use by screen readers that speak the content aloud. In this article, I’ll talk first about designing for variable font and screen sizes on Android.
Always use “scale-independent pixels” for font measurement
When you’re working with TextView, you’ve probably seen Android Studio warn you when you use a font size measurement other than sp , or “scale-independent pixels”. Here’s what happens when you use dp (density-independent pixels) instead:
This message is generated by the linter provided by the Android build tools. The full lint message is this (emphasis mine):
When setting text sizes, you should normally use sp, or “scale-independent pixels”. This is like the dp unit, but it is also scaled by the user’s font size preference. It is recommended you use this unit when specifying font sizes, so they will be adjusted for both the screen density and the user’s preference.
There are cases where you might need to use dp; typically this happens when the text is in a container with a specific dp-size. This will prevent the text from spilling outside the container. Note however that this means that the user’s font size settings are not respected, so consider adjusting the layout itself to be more flexible.
While dp is common for measuring everything else on screen, using sp is better for text for one important reason: it lets the user change the size of the font to suit their preferences. Here’s what the font size preference screen looks like on Android N emulators, both the normal and maximum font sizes:
(With these screens I’m showing, you should try to size them to match a 5 inch phone display to get the intended effect.)
For those of us with normal or corrected vision, the default font size is likely OK. It might never occur to you to change this. However, for people with poor vision (who are not legally blind, or can’t have their vision corrected to normal), increasing the font size matters greatly. Here, I’ll apply the same amount of blur to each screen that simulates what poor vision might be like:
(Note that visual impairment is more complicated than blurry vision — this is only an approximation.)
No matter how good your vision is, the normal font size is almost completely unreadable here. However, the larger size (while still a bit fuzzy) is actually somewhat readable. If you use sp as a font measurement uniformly throughout your app, you’re enabling people with poor or uncorrected vision to more easily use your app. And you’re definitely meeting the preferences of people who simply prefer larger text. High quality mobile app designs allow for (and expect!) the size of the text to change without impacting the usability and presentation of the app. Please note that allowing for adjustable font sizing is not really enabling full “accessibility”, but it’s part of designing an app that looks and works well for as many people as possible.
Design for adjustable font sizes
Android provides some facilities to make it easier to adjust layouts to variable font sizes. If you’re a designer, it’s important to incorporate these into your designs, and if you’re an engineer, you’ll need to keep an eye out for potential problems that a designer might have missed.
Strict height constraints? Limit overflow text.
One thing you’ll quickly realize, as font sizes can vary, is that your pixel-perfect designs might become annoyingly imperfect. If you’re designing and implementing screens around the specific size of some text, that’s likely going to cause problems as the font size changes (or even on other devices that don’t share the exact same dimensions). So it’s a good idea to abandon rigid designs, and allow for flexibility.
One common design requirement is for all the elements in a scrolling list to be the same height. This is fine. However, if you assume all the text will fit on the same one or two lines, that design could break as the font or text grows. For these cases, a better idea is to:
- Cap (or force) the number of lines of text that a TextView must render
- Ellipsize any overflow text
- Allow for a gesture to expand or disclose any missing information. This could be as simple as tapping to get a popup with the complete information.
So, if you want to allocate exactly two lines of text with ellipsized overflow, your TextView will be configured like this:
Note the use of android:lines to fix the height of to a certain number of lines, and android:ellipsize to render ellipses at the end of the text when it overflows the allocated space. As the text and font varies, your relative size constraints won’t be violated. Here’s a RecyclerView with constant height items being truncated as necessary, depending on the chosen font size:
Источник