Оптимизируйте свои подборки
Сохраняйте и классифицируйте контент в соответствии со своими настройками.
Вы можете стилизовать части текста, чтобы улучшить читаемость, повысить положительный пользовательский опыт и стимулировать творческий подход за счет использования цветов и шрифтов.
Совместимость версий
Для этой реализации требуется, чтобы для minSDK вашего проекта был установлен уровень API 21 или выше.
Зависимости
Оформление частей текста
Следующий код отображает строку «Hello World», используя синий цвет для буквы «H», красный для буквы «W» и черный для остального текста. Чтобы установить разные стили в одном компонуемом Text , используйте следующий код:
Стилизует часть текста с помощью SpanStyle — конфигурации, позволяющей стилизовать на уровне символов.
Результаты
Рисунок 1. Строка текста с несколькими стилями.
Коллекции, содержащие это руководство
Это руководство является частью тщательно подобранной коллекции быстрых руководств, охватывающих более широкие цели разработки Android:
Отображать текст
Текст — центральная часть любого пользовательского интерфейса. Узнайте, как можно представить текст в своем приложении, чтобы обеспечить приятный пользовательский опыт.
Контент и образцы кода на этой странице предоставлены по лицензиям. Java и OpenJDK – это зарегистрированные товарные знаки корпорации Oracle и ее аффилированных лиц.
Последнее обновление: 2025-02-22 UTC.
[[["Прост для понимания","easyToUnderstand","thumb-up"],["Помог мне решить мою проблему","solvedMyProblem","thumb-up"],["Другое","otherUp","thumb-up"]],[["Отсутствует нужная мне информация","missingTheInformationINeed","thumb-down"],["Слишком сложен/слишком много шагов","tooComplicatedTooManySteps","thumb-down"],["Устарел","outOfDate","thumb-down"],["Проблема с переводом текста","translationIssue","thumb-down"],["Проблемы образцов/кода","samplesCodeIssue","thumb-down"],["Другое","otherDown","thumb-down"]],["Последнее обновление: 2025-02-22 UTC."],[],[],null,["\u003cbr /\u003e\n\nYou can style parts of text to improve readability, increase positive user\nexperience, and encourage greater creativity through use of colors and fonts.\n\nVersion compatibility\n\nThis implementation requires that your project minSDK be set to API level 21 or\nhigher.\n\nDependencies\n\nStyle parts of text\n\nThe following code displays the string \"Hello World\" using blue for the \"H\", red\nfor the \"W\", and black for the rest of the text. To set different styles within\na single [`Text`](/reference/kotlin/androidx/compose/material/package-summary#Text(androidx.compose.ui.text.AnnotatedString,androidx.compose.ui.Modifier,androidx.compose.ui.graphics.Color,androidx.compose.ui.unit.TextUnit,androidx.compose.ui.text.font.FontStyle,androidx.compose.ui.text.font.FontWeight,androidx.compose.ui.text.font.FontFamily,androidx.compose.ui.unit.TextUnit,androidx.compose.ui.text.style.TextDecoration,androidx.compose.ui.text.style.TextAlign,androidx.compose.ui.unit.TextUnit,androidx.compose.ui.text.style.TextOverflow,kotlin.Boolean,kotlin.Int,kotlin.Int,kotlin.collections.Map,kotlin.Function1,androidx.compose.ui.text.TextStyle)) composable, use the following code:\n\n\n```kotlin\n@Composable\nfun MultipleStylesInText() {\n Text(\n buildAnnotatedString {\n withStyle(style = SpanStyle(color = Color.Blue)) {\n append(\"H\")\n }\n append(\"ello \")\n\n withStyle(style = SpanStyle(fontWeight = FontWeight.Bold, color = Color.Red)) {\n append(\"W\")\n }\n append(\"orld\")\n }\n )\n}https://github.com/android/snippets/blob/7a0ebbee11495f628cf9d574f6b6069c2867232a/compose/snippets/src/main/java/com/example/compose/snippets/text/TextSnippets.kt#L233-L248\n```\n\n\u003cbr /\u003e\n\nKey points about the code\n\n- Uses [`buildAnnotatedString`](/reference/kotlin/androidx/compose/ui/text/package-summary#buildAnnotatedString(kotlin.Function1)) that returns an [`AnnotatedString`](/reference/kotlin/androidx/compose/ui/text/AnnotatedString) string to set different styles within text.\n- Styles part of text with [`SpanStyle`](/reference/kotlin/androidx/compose/ui/text/SpanStyle), a configuration that allows character-level styling.\n\nResults **Figure 1.** A line of text with multiple styles.\n\nCollections that contain this guide\n\nThis guide is part of these curated Quick Guide collections that cover\nbroader Android development goals: \n\nDisplay text \nText is a central piece of any UI. Find out different ways you can present text in your app to provide a delightful user experience. \n[Quick guide collection](/develop/ui/compose/quick-guides/collections/display-text) \n\nHave questions or feedback \nGo to our frequently asked questions page and learn about quick guides or reach out and let us know your thoughts. \n[Go to FAQ](/quick-guides/faq) [Leave feedback](https://issuetracker.google.com/issues/new?component=1573691&template=1993320)"]]