Coders' Guidebook

How to add and style text in your Android app

Text allows us to display information to the user. The easiest way to add text to your app is to incorporate it directly into XML layout files such as activity_main.xml. This file will often already be open when the app is loaded, but if it is not (or you wish to open up a different XML file) then simply go to Project > app > res > layout

activitymain.png

Make sure you are viewing the XML file in Design mode then open up the Palette. Explore the Text category and locate the TextView object. Drag and drop it onto the desired location in the editor window.

textdrop.png

By default, the text shown by the object will be "TextView". To change this, select the TextView object by left-clicking on it then refer to the Attributes menu on the right-hand side of the editor. In the list of Declared Attributes, there will be one called text. Edit the value of the text attribute to the text of your choosing. In the example below, the message has been changed to "My first app".

firsttext.png

Text size

Now you have added some text to our app, you can begin to style it. The first thing you may want to do is edit the size of the text. To do this, select the TextView object by left-clicking on it then locate its textSize attribute. You can locate specific attributes by scrolling down the list of All Attributes; however, it is often quicker to use the search bar at the top of the Attributes panel.

textsize.png

By default, the textSize attribute will be set to 14sp but you can make it smaller or larger depending on your preference. The 'sp' unit stands for Scale-independent Pixels. Declaring text sizes in sp mean they will scale accordingly when the user alters the font size in their devices' settings. This is useful for people who need larger/smaller text. If you do not want your text to rescale then use the unit dp (Density-independent Pixels) instead.

textsizes.png

<<< Previous

Next >>>