Looking For Anything Specific?

[Tutorial] How to Customize Android TextView in XML

Hello fellow readers,

In this long tutorial, I am going to explain in detail android's TextView by using almost all the attributes available for android TextView to make your application's User Experience better. For this guide, I am going to use android's constraint layout for the design, which is one of the powerful layouts in android, which gives us complete control over arranging the views without making the XML more complex by nesting linear and relative layouts. And if you don't know the full potential of the android's constraint layout here is the guide which will help you understand.

You May Have Missed:


Now that you are a pro in constraint layout, let's start with one of the basic and most used android view components/widgets which is android's TextView. TextView is nothing but a holder that displays the text in the application. Because of that, it is used across the application. So this key component is the one that will attract the user to your application and improve the users' experience, so we better make this a beautiful on. Although I can't cover all the functionalities in this single article, so there will be a PART-2 of this article in near future, but still, I have done my best to pick up some of the most used functionalities that every application must have and will be using. So let's get started...

Android TextView Basic With Constraint Layout

Well, let's start with the basics, by creating a new project in android or you can download my code below after that begin with adding some TextView's to your layout well if you're going to follow this tutorial I will say add five TextView because we are going to add one design or functionality to each. After adding five TextView go to the design tab in android studio and select first our TextView and right-click on them and there some options provided by android constraint layout in that we are going to use the "Chains" option which will group the selected elements and align them one after another either vertical or horizontal orientation, for this guide we are going to use the vertical chain so click  "Create Vertical Chain" then you will see the TextVieware placed with equal space in between them now let's improve our TextView by adding fonts, rounded corner in the background and adding some runtime functionalities.

You might have missed:

How to set the font in android TextViewin XML:

To set the font in your android text views, we need the font in our application first so I have written a brief post about how to add a custom font to your android application here, you can follow the link to learn more about how to add fonts and set fonts to Android TextView. Still, I will here also share how to set the font to android TextView in XML  To set fonts to your TextView you can use the android fontFamily attribute,

android:fontFamily="@font/opensans_bolditalic"

And set the font name to your font name, make sure you're following this guide to our guide on How to set custom fonts to the android application in case if you run into any errors. Adding fonts is easy and fun, it also increases the uniqueness of your application. Then how about adding some more cool improvements to your TextView, that we are going to customize the TextViewwith rounded corners and with an icon on the left

How to make android text background in rounded corners

There is one attribute in android XML that will help us to set background for TextView, but not only TextView this attribute is supported by other views to like buttons, layouts, and so on. which is android:background="", the attribute which will allow us to set either a color, a vector, or a drawable to a view component. With the help of this attribute, we can able to set a drawable to TextView as background.

how to set rounder corner to andorid textview


Now are going to make a rounded corner drawable and set it to the TextView's background

  • To create a rounded corner drawable:
  • Go to the project tab in the sidebar
  • Expand the res folder and Right-click on the drawable folder
  • Choose New -> Drawable resource file
  • And name it as rounded_corner 
  • Then click ok

If you open the drawable file you will see only a selector tag in that file, which we are not going to use for this tutorial so you can clear the complete file including the XML version tag. Or you can change the selector tag to shape tag and define the android:shape attribute as rectangle like this android:shape="rectangle", other than rectangle there are three other shapes supported by android which are ring, oval, and line, for now, we only need the rectangle because that's what we are going to need to achieve our design.

Then inside the shape tag and two more tags one for corner and another for a color like below

<corners android:radius="8dp"/>
<solid android:color="@color/colorAccent"/>

The corner tag allows us to set the radius to the drawable which has the rectangle share, so always consider setting the radius as 1/4 of the height of the view because let's say that the view's height is 32dp and you're setting the radius as 16dp then it will give more like a capsule share rather than a rounded corner. So if your view's height is 32dp then set the radius as 8dp. And to set color we can use the solid tag to set a color to the complete view you can also make gradients which will be discussed in another post.

So the complete rounded_corner.xml file must look like this

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
<corners android:radius="16dp"/>
<solid android:color="@color/colorAccent"/>

</shape>

Now that we have our rounder corner drawable we can add this to our text view as a background as
android:background="@drawable/rounded_corner" To make the text view more interesting we are going to add an icon to the left side of the TextView, we can achieve the above design in three ways, one by adding a new ImageView and set the constraint to match the TextViewbut it adds an extra tag also that might hard to maintain the code and we have to add a click listener for both the views so we are not going to do that, the second way is to create a linear layout and put the image view and the TextViewinside this may solve one problem instead of adding two click listeners it reduces to one, but again it makes the code even more complex in the XML file so we are not going to use it either instead we are going to use the third way which is adding drawable / icons to the android TextViewwith the drawable attribute which has six, android:drawableStart, android:drawableLeft, android:drawableTop, android:drawableEnd, android:drawableRight, android:drawableBottom. These are the six attributes that we can use to set a drawable to android TextView, we can easily understand the four attributes but there is two which might look like a new which is drawableStart and drawableEnd which are nothing but an alternative to left and right provided by android to support LTR and RTL languages so in general the start is left and the end is right.

How to add drawable to android TextView

For this tutorial, instead of spending some time in photoshop/ Krita /GIMP, I am going to use the android studios vector asset creator trust me it has all the icons which you need for your app and the are lots of advantage in using a vector asset so create an android vector asset of your choice with android studio.

Now use the android:drawableStart attribute to set the icon to the beginning of the text.  Your TextView will not look as much as the one here that's because there is still room for improvement which means we have to add some attributes which are android:padding and android:drawablePadding this will give some space between the text and icon. Like this. But see the text is not properly aligned with the icon.

So in order to align TextView's text with the drawable, we need to add another attribute which is the android:gravity which will align the text some more, so for that set the gravity as center_vertical.

    <TextView
        android:id="@+id/textThree"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/rounded_corner"
        android:drawableStart="@drawable/ic_cloud_done_black_24dp"
        android:drawablePadding="16dp"
        android:gravity="center_vertical"
        android:padding="16dp"
        android:text="@string/rounded_corner_backgrounds"
        android:textAlignment="center"
        android:textColor="#FFFFFF"
        android:visibility="visible"
        app:layout_constraintBottom_toTopOf="@+id/textFour"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textTwo" />

Above is the code to set a drawable to the TextView, this will make the drawable and the text properly aligned

How to set the font in android programmatically

Previously we have seen how to set a custom font to android text in XML now we can learn about how to change the font of android text programmatically. Along with that, we are going to use one of the useful features of the android constraint layout which is the baseline property.

Constraint layout's baseline attribute will help us to align the text in a single line, let's say you have two TextView in different sizes one after another and you want to place both the TextView in a single line and that's where the baseline attribute comes in the picture. It helps to keep the text in a single line like how we write on paper. To do that all you have to do is add an app:layout_constraintBaseline_toBaselineOf to the text view which you to be aligned with another and pass the id of the first TextView. If you see in the design view in the android studio you might see a blue bar below the text connected.

how to set custom font in android textview programmatially


Once we connect the baseline the text will be perfectly aligned to another text, then we can set a click listener to our TextView. I have shared a complete tutorial on how to set an onClick listener to a button here, you can follow that to set an onClick listener to the TextView.

You might have missed:


Now that we have an onClick listener set to our TextView we can now change the font of the on the click action for that we are going to use the setTypeFace() method.

textThree.setOnClickListener {
            if(Build.VERSION.SDK_INT >= 26){
                textFive.typeface = resources.getFont(R.font.opensans_bolditalic)
            }else{
                textFive.typeface = ResourcesCompat.getFont(applicationContext,R.font.opensans_bolditalic)
            }

        }

Above is the code to the font of a text view programmatically at run time what this piece of code is doing is, the textThree is a TextView for which I have set a click listener. Then I get the font from the resource folder and set it to another TextView with the id textFive, simple as it is

How to set drawable to android TextView programmatically:

Before in this very post, we have set a drawable to our TextView using XML, here we are going to set/change the drawable at runtime programmatically. in order to do that we are going to use the method called setCompoundDrawablesRelativeWithInstrinsicBounds(star, top, end, bottom).

textFour.setOnClickListener {
            (it as  TextView).apply {
                setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,R.drawable.ic_done_black_24dp,0)
            }

        }

In this method, we can set a drawable to a TextView at runtime, programmatically.  Also, we can position the drawable at our sides of the view. So if you want to set the drawable to right side only like when a user clicks the TextView and showing a confirmation as done, you need to reference the drawable file to as third parameter and the rest a 0, So then only the drawable will be set to left and the other sides will be the same.

Quick Tip: In order to remove the drawable from a TextView at runtime, call the above method and by-passing all the parameters as 0. like this: setCompoundDrawablesRelativeWithIntrinsicBounds(0,0,0,0)


Below is the complete output of the screen:

kotlin andorid textview tutorial


You are welcome to get my code:
GDrive: Download Code


!!!Spread The Word!!!

keywords: