Introduction to Dimension Variables: Android Studio Crash Course (Free Tutorial)

Welcome! Ready to get a leg up on the competition? This article will teach you how to change the size of the text in your application FASTER than ever. If you are a beginner and are looking for an introduction to coding, check out our FREE 30-minute course here: training.mammothinteractive.com/p/learn-to-code-in-30-minutes

To follow along with this example in Android Studio, go into Project view. Then go to app > res > layout, and open “activity_main.xml”. Also, in the “values” folder in “res”, select “dimens.xml (2)”.

We’ll begin with “activity_main.xml” in Design mode, which lets us drag and drop items into our application. Select two of “Plain TextView” from the Widgets folder on the left-hand side. Position the two widgets just under the “Hello World!” text already on the screen. Your display should have three lines of text:

Hello World!
New Text
New Text

In this example, we will be changing the font size of these three lines of text. In Text mode, let’s first look at assigning size the long way. Add the following beneath android:id="@+id/textView2":

android:textSize="50sp"

Make sure this line is within the topmost TextView tag. Next, copy and paste this line into the other two TextView tags.

Now, let’s say we’re not happy with our text size of 50sp. What if we want to change it to 20sp? As you can imagine, changing 50sp to 20sp manually isn’t the favored technique. If you have a large number of TextViews, it is too tedious to change them one by one.

Thus, it’s much more efficient to reference a dimension variable. These variables are declared in the “dimens.xml” file.

In that file, in the resources tag, create a dimension variable using the keyword dimen, and name it "textSize". Also, give this variable the value 50sp. Finally, close the tag. Your line of code should look like this:


The next step is to go back to the activity_main file and reference our dimension resource. To do this, write @dimen/textSize instead of 50sp in all three TextViews.

Now if we want to change the text size to 20, we don’t have to go to each TextView in our application and correct the value manually. We can just go the resources tag in our dimension file and change 50 to 20.

Great work! With this skill, your programming will be faster and more efficient. For more FREE tutorials, check out our 30-minute beginners course on coding: training.mammothinteractive.com/p/learn-to-code-in-30-minutes

Mammoth Interactive Favicon

Why you NEED to take this course :

Get in Touch.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

EMAIL US

support@mammothinteractive.com