How to Set the Text Color of TextView in Code?
One of the most often used User Interface elements is TextView. The user experience is improved, and the application looks better, due to the clear and organized text. It doesn’t matter what kind of information is being shown, it should always be done well. In an android app, TextView allows us to do this, thus understanding its properties is crucial.
There are two methods of changing the color of a TextView and the code for that has been given in both Java and Kotlin Programming Language for Android, so it can be done by directly adding a color attribute in the XML code or we can change it through the MainActivity File. By default, the color of the text will be black until it is changed.
How to change Text Color of TextView in Android?
TextView Text Color – To change the color of text in TextView, you can set the color in layout XML file using textColor attribute or change the color dynamically in Kotlin file using setTextColor() method.
In this tutorial, we will learn both the layout file approach and Kotlin line approach to change the text color of TextView.
Change Text Color of TextView via XML Layout File
textColor attribute of TextView widget lets you set a color of your choice. You can provide the color as hex value in one of the four formats: rgb, argb, rrggbb, or aarrggbb.
The syntax to set textColor attribute for TextView using different color formats is
Example 1 – TextView Color
Let us create an Android application with Kotlin support in Android Studio and change the text color of TextView in XML layout file.
activity_main.xml
We have used a string resource, and the contents of strings.xml is
There is no need to change the MainActivity.kt file. The default code would do.
MainActivity.kt
Run this application, and you would get the following screenshot.
Change Text Color of TextView in Kotlin File
We can get the reference to TextView widget present in layout file and change the color dynamically with Kotlin code.
To set the color to the TextView widget, call setTextColor() method on the TextView widget reference with specific color passed as argument.
setTextColor() method takes int as argument. Use android.graphics.Color class to get an integer for a given color. You can provide the color as hex value in one of the four formats: rgb, argb, rrggbb, or aarrggbb.
The syntax to set text color using setTextColor() method of TextView in Kotlin Activity file is
Example 2 – TextView Color
Let us create an Android application with Kotlin support in Android Studio and change the text color of TextView dynamically/programmatically in Kotlin file.
The layout file contains a TextView. Since we are about to change the text color in Kotlin file, no text color is specified in layout XML file.
activity_main.xml
We have used a string resource, and the contents of strings.xml is
We have got the reference to the TextView in layout file using findViewById() method. Call to setTextColor() method on the TextView reference would set the text color of TextView.
MainActivity.kt
Run this application, and you would get the following screenshot.
Conclusion
In this Kotlin Android Tutorial, we learned how to set or change the text/font color of TextView widget in Android application.
Как изменить цвет текста в андроид студио
В приложении Android также можно определять ресурсы цветов (Color). Они должны храниться в файле по пути res/values и также, как и ресурсы строк, заключены в тег <resources> . Так, по умолчанию при создании самого простого проекта в папку res/values добавляется файл colors.xml :
Цвет определяется с помощью элемента <color> . Его атрибут name устанавливает название цвета, которое будет использоваться в приложении, а шестнадцатеричное число — значение цвета.
Для задания цветовых ресурсов можно использовать следующие форматы:
#RGB (#F00 — 12-битное значение)
#ARGB (#8F00 — 12-битное значение с добавлением альфа-канала)
#RRGGBB (#FF00FF — 24-битное значение)
#AARRGGBB (#80FF00FF — 24-битное значение с добавлением альфа-канала)
Чтобы не трогать и не портить данный файл, определим свой новый файл ресурсов и для этого добавим в папку res/values новый файл ресурсов, который назовем my_colors.xml .
Изменим файл my_colors.xml , добавив в него пару цветов:
Применим цвета в файле activity_main.xml :
С помощью атрибута android:textColor устанавливается цвет текста в TextView, а атрибут android:background устанавливает фон TextView. В качестве значения они используют цвет, например, в том же шестнадцатеричном формате. Для получения самого цвета после «@color/» указывается имя ресурса.
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?
Which to use and when?
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 <Button> 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 <item name="buttonStyle">@style/Widget.Material.Light.Button</item> 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.