How to Change TextView Size Programmatically in Android?
A TextView in Android is a UI element to display text. It can be programmed in the layout file statically as well as in the main code dynamically. Thus, various attributes of a TextView such as the text, text color, text size, TextView background, and its size can be changed programmatically. In this article, we will show you how you could programmatically change TextView size in Android.
In the sample application that we have demonstrated in this article, there are two UI elements that are a TextView and a Button. We have programmed the Button in such a way that with every click, the TextView dimensions are doubled. Meaning, for, before that first click, the TextView length and height are 50 sp and 50sp. After the first click, the dimensions become 100sp. On the second click, the dimensions are 200sp. for length and height. Now follow the below steps to create this application.
Note: This method of changing the TextView size can also be applied to other UI elements.
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. We have declared a TextView of 50sp x 50sp and a Button.
Step 3: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. In the main code, we have programmed the Button in such a way that if it is clicked, the current layout parameters of the TextView, i.e. the width and the height are multiplied by 2. Comments are added inside the code to understand the code in more detail.
We can see that at every Button click, the TextView layout dimensions are doubled from their previous values.
Please Login to comment...