- 400+ Android & Flutter Code
- Monday, January 5, 2015
- How to display bold text in a TextView in android
- TextView bold text programmatically
- Как изменить текст на жирный в Android?
- Как изменить текст на жирный шрифт в Android?
- ОТВЕТЫ
- Ответ 1
- Ответ 2
- Ответ 3
- Ответ 4
- Ответ 5
- Ответ 6
- Ответ 7
- Ответ 8
- Ответ 9
- Ответ 10
- Ответ 11
- Ответ 12
- Ответ 13
- Ответ 14
- Ответ 15
- Ответ 16
- Ответ 17
- Ответ 18
- Как изменить текст на жирный шрифт в Android?
- Styling internationalized text in Android
- Basic text styling with HTML tags
- Complex text styling with Annotation
- Bonus section: Annotation spans and text parceling
- Underspanding spans
- Spans are powerful concepts that allow styling text at character or paragraph levels by providing access to components…
400+ Android & Flutter Code
Example code for android + flutter app developers.
Monday, January 5, 2015
How to display bold text in a TextView in android
TextView widget display text on android app. we can render a TextView to display text as bold or italic both programmatically by java file and syntactically by xml layout file. we also can bold TextView text syntactically by using string ressource file. this first android app demonstrate us how can we render TextView text bold, italic, normal and even underlined by declarative syntax.
the android:textStyle attribute allow us to set the text style to normal, bold or italic. we can combine this style by separated them using keyboard pipe | symbol. so if we want to render TextView text as bold and italic then we need to set the android:textStyle attribute value as android:textStyle=»blod|italic». android:textStyle=»normal|italic» value display text as italic, android:textStyle=»bold» value display text only bold and android:textStyle=»normal» value define TextView text appearance as normal.
this is very interesting that we can render a TextView’s part of text as bold, italic or underlined by using string resource file. the string resource file allow us to declare a string resource which value contain html tags. so the final output show the stylish text on android app. strings.xml resource file exist under res/values folder.
in the following example code, we declare a string key value pair name stylish_text and its value. stylish_text key’s value contain html tags those make part of text bold, italic and underlined. in the xml layout file we can assign the string resource as android:text=»@string/stylish_text».
TextView bold text programmatically
the following android example app code demonstrate us how can we bold, italic or underline TextView text programmatically at run time in java file.
setTypeface() method allow us to set the typeface and style in which the text should be displayed in a widget. all Typeface families have not bold and italic variants. geTypeface() method allow us to get the current typeface and style in which the text is being displayed. we can define a TextView widget’s font and font variant by the setTypeface() method as setTypeface(Typeface.MONOSPACE, Typeface.BOLD_ITALIC). the setTypefce() method only render a TextView text to bold, italic and normal. it does not support underline text or any other formatting.
if we want to display bold and underlined text programmatically on an app, we need to take help the setText() method. to do this, we need to provide html tags with text as setText() method parameter. the setText() method render the html tags and display formatted text on application.
another way to render TextView text bold programmatically in java code by using style resource file. we can put a styles.xml file on res/values folder. then assign styles item and value to the style file. finally we can apply any style from this style file to the TextView by using the setTextAppearnce() method.
setTextAppearance() method allow us to set the text color, size, style, hint color etc from the specified TextAppearance resource.
Источник
Как изменить текст на жирный в Android?
Как изменить настройки текста / шрифта в Android TextView ?
Например, как вы делаете текст жирным ?
Для этого в layout.xml файле:
Программно метод состоит в следующем:
Устанавливает шрифт и стиль, в котором должен отображаться текст. Обратите внимание, что не во всех Typeface семьях есть варианты, выделенные жирным шрифтом и курсивом, поэтому вам, возможно, придется использовать их, setTypeface(Typeface, int) чтобы получить тот вид, который вам действительно нужен.
Просто вы можете сделать следующее:
Установите атрибут в XML
Программно метод заключается в:
Надеюсь, это поможет вам поблагодарить вас.
Вы можете использовать только определенные шрифты sans , serif и monospace через XML, код Java может использовать пользовательские шрифты
Программно (код Java)
Для случая, когда вы используете пользовательские шрифты, но не имеете жирного шрифта для шрифта, который вы можете использовать:
Это очень просто
Если вы рисуете это, то это сделает это:
В идеальном мире вы бы задали атрибут стиля текста в своем определении XML макета следующим образом:
Существует простой способ динамического достижения того же результата в вашем коде с помощью setTypeface метода. Вам нужно передать и объект класса Typeface , который будет описывать стиль шрифта для этого TextView. Таким образом, чтобы достичь того же результата, что и в приведенном выше определении XML, вы можете сделать следующее:
Первая строка создаст объект в предопределенном стиле (в данном случае Typeface.BOLD , но есть еще много ). Когда у нас есть экземпляр гарнитуры, мы можем установить его в TextView. И это все, что наш контент будет отображаться в стиле, который мы определили.
Я надеюсь, что это вам очень поможет. Для более подробной информации вы можете посетить
Из XML вы можете установить TextStyle к жирному шрифту , как показано ниже
С программной точки зрения, вы можете установить TextView жирным шрифтом, как показано ниже
Определите новый стиль с нужным форматом в файле style.xml в папке значений
Затем примените этот стиль к TextView, написав следующий код со свойствами TextView.
Источник
Как изменить текст на жирный шрифт в Android?
Как изменить текст/шрифт в Android TextView ? Например, как сделать текст жирным?
ОТВЕТЫ
Ответ 1
Чтобы сделать это в файле layout.xml :
Устанавливает шрифт и стиль, в котором должен отображаться текст. Обратите внимание, что не все семейства Typeface имеют жирный и курсивный варианты, поэтому вам может понадобиться использовать setTypeface(Typeface, int) , чтобы получить тот внешний вид, который вы действительно хотите.
Ответ 2
Ответ 3
Просто вы можете сделать следующее:
Установите атрибут в XML
Программно этот метод:
Надеюсь, это поможет вам поблагодарить вас.
Ответ 4
Вы можете использовать только определенные шрифты sans , serif и monospace через xml, код Java, чтобы использовать пользовательские шрифты
Программно (код Java)
Ответ 5
Ответ 6
В случае, когда вы используете пользовательские шрифты, но не имеете полужирного шрифта для шрифта, который вы можете использовать:
Ответ 7
Это очень легко
Ответ 8
Если вы его рисуете, то это будет делать:
Ответ 9
В идеальном мире вы должны установить атрибут стиля текста в своем XML-определении макета следующим образом:
Существует простой способ добиться того же результата динамически в вашем коде с помощью метода setTypeface . Вам необходимо передать и объект класса Typeface, который описывает стиль шрифта для этого TextView. Таким образом, чтобы достичь такого же результата, как и в определении XML выше, вы можете сделать следующее:
Первая строка создаст предопределенный стиль формы объекта (в данном случае Typeface.BOLD, но есть еще много предопределенных). Когда у нас есть экземпляр шрифта, мы можем установить его в TextView. И что это наш контент будет отображаться в стиле, который мы определили.
Надеюсь, вам это поможет. Для получения более подробной информации вы можете посетить
Ответ 10
Определите новый стиль с нужным вам форматом в файле style.xml в папке значений
Затем примените этот стиль к TextView, написав следующий код со свойствами TextView
Ответ 11
Ответ 12
Предполагая, что вы новый стартер на Android Studio, Просто вы можете сделать это в представлении дизайна XML, используя
Ответ 13
Вы можете использовать это для шрифта
создать имя класса TypefaceTextView и расширить TextView
private static Map mTypefaces;
вставьте шрифт в папку шрифтов, созданную в папке с ресурсами
Поместите строки в родительский макет в xml
Ответ 14
в файле .xml установите
установит тип текста жирным шрифтом.
Ответ 15
В моем случае передача значения через string.xml с помощью HTML-тега.
Ответ 16
Использование атрибута android: textStyle
Используйте полужирный | курсив для полужирного и курсивного.
используя метод setTypeface()
Метод HtmlCompat.fromHtml(), Html.fromHtml() устарел на уровне API 24.
Ответ 17
установит как шрифт, так и стиль шрифта Bold.
Ответ 18
Из XML вы можете установить textStyle жирным шрифтом, как показано ниже
С программной точки зрения, вы можете установить TextView жирным шрифтом, как показано ниже
Источник
Как изменить текст на жирный шрифт в Android?
Как изменить настройки текста / шрифта в Android TextView ? Например, как сделать текст полужирным ?
Для этого в файле layout.xml :
Устанавливает шрифт и стиль, в котором должен отображаться текст. Обратите внимание, что не все семейства Typeface имеют жирный и курсивный варианты, поэтому вам может понадобиться использовать setTypeface(Typeface, int) чтобы получить видимость, которую вы действительно хотите.
Просто вы можете сделать следующее:
Установить атрибут в XML
Программно этот метод:
Надеюсь, это поможет вам поблагодарить вас
Вы можете использовать только специальные шрифты sans , serif & monospace через xml, код Java может использовать пользовательские шрифты
Программно (код Java)
Если вы его рисуете, это сделает это:
Это очень легко
Для случая, когда вы используете пользовательские шрифты, но не имеете полужирного шрифта для шрифта, который вы можете использовать:
В идеальном мире вы бы установили атрибут стиля текста в вашем XML-определении макета:
Существует простой способ добиться того же результата динамически в вашем коде с помощью метода setTypeface . Вам нужно передать и объект класса Typeface , который будет описывать стиль шрифта для этого TextView. Таким образом, чтобы достичь такого же результата, как и в определении XML выше, вы можете сделать следующее:
Первая строка создаст предопределенный стиль формы объекта (в данном случае Typeface.BOLD , но есть еще много предопределенных). Как только у нас есть экземпляр шрифта, мы можем установить его в TextView. И вот наш контент будет отображаться в стиле, который мы определили.
Надеюсь, вам это поможет. Для получения более подробной информации вы можете посетить
Определите новый стиль с нужным вам форматом в файле style.xml в папке значений
Затем примените этот стиль к TextView, написав следующий код со свойствами TextView
Вы можете использовать это для шрифта
Создать имя класса TypefaceTextView и расширить TextView
Приватная статическая карта mTypefaces;
Вставьте шрифт в папку шрифтов, созданную в папке с ресурсами
Поместите строки в родительский макет в xml
Источник
Styling internationalized text in Android
In a previous article we talked about styling characters or paragraphs in Android using spans. But all the examples used were based on hard coded text, where we knew exactly at which indexes to apply the span. Most of the time, the text we work with comes from resources and is internationalized. So the text we need to style and its positioning within a sentence may change.
For example, let’s say that we have the string “ Best practices for text on Android” in English and Spanish, and we want to style the word “ text”.
We end up having to style different words, “ text” and “ Texto”, that have different positions in the strings they belong to, so looking for occurrences of a specific word is not a feasible task. Depending on what kind of styling we want to apply, we have multiple ways of styling internationalized text: by using HTML tags or using the Annotation span together with the annotation tag.
Basic text styling with HTML tags
If you only want to apply basic styling, use HTML tags in the string resources or Html.fromHtml . The following styling is supported:
- Bold: ,
- Italic: , ,
- 25% increase in text size
- 20% decrease in text size
- Setting font properties: . Examples of the possible font families include monospace , serif and sans_serif .
- Setting a monospace font family:
- Strikethrough:
,, - Underline:
- Superscript:
- Subscript:
- Bullet points:
- ,
- Line breaks:
- Division:
For example, to have the word “ text” bold, the text in the strings.xml would be this:
In the UI, the text can be set like this:
Complex text styling with Annotation
If your styling needs exceed the capabilities supported by HTML tags, or if you want to use custom styles, like custom bullet point styling or even completely new styles, then we need another solution. Mark the words to be styled and work with the android.text.Annotation class and the corresponding tag in the strings.xml resource files.
The annotation tag allows us to define custom pairs in the xml. When getting string resources as SpannedString , these pairs are automatically converted by the Android framework into Annotation spans, with the corresponding key and value. We can then parse the list of annotations attached to the text and add the right span to our text.
Let’s say that we want to set a custom typeface, by applying a CustomTypefaceSpan to the word “text”. Here’s what we need to do:
2. Get the string from resources, iterate through the annotations and get the ones with the key font and the corresponding value. Then create the custom span and set it to text in the same positions as the annotation span.
You can find the complete code for this example here.
For a more complex example, in Java, using Annotations to add an image to the text and to set the foreground color, check out this commit from Plaid.
If you’re using the same text several times, for example in a RecyclerView , and you reconstruct the SpannableString for every item, there are some performance and memory implications you need to keep in mind:
- The string is iterated multiple times: once by the framework to add the Annotation spans and once by you, to manually add your spans
- A new instance of the SpannableString is created for every item.
To solve this, build the text only once, cache and then reuse the SpannableString .
Bonus section: Annotation spans and text parceling
In a previous article we mentioned that only framework spans are parceled when styled text is passed either in the same process (via Intent bundles, for example) or in between processes (by copying text).
Underspanding spans
Spans are powerful concepts that allow styling text at character or paragraph levels by providing access to components…
Because Annotation spans are also ParcelableSpan s, then the pairs are parceled and unparceled, making the Annotation span a way of applying custom styling to text that is parceled, as long as the receiving end knows how to interpret the annotations.
So, to keep your custom styling when you pass the text to an Intent Bundle, you first need to add Annotation spans to your text. You can do this in the XML resources via the tag, like shown above, or in code by creating a new Annotation and setting it as a span:
Retrieve the text from the Bundle as a SpannableString and then parse the Annotations attached, like in the example above.
For simple styling of internationalized text, update your string resources to use HTML tags. But when your styling needs exceed the limits of the supported HTML tags, use the Annotation span and the associated annotation tag. As an extra benefit, the Annotation spans are parcelable, so you can style your text easily, no matter how you work with it.
For more best practices with text, checkout the Google I/O 2018 talk:
Источник