If the user is giving the input and the input needs to be shown as TextView and if the user inputs the stuff which can go out of the screen, then in this case the font TextView should be decreased gradually. So, in this article its been discussed how the developer can reduce the size of TextView gradually as the user gives the data. One can have a look at the following GIF to understand it better, what we are going to build at the end of this article. Note that we are going to implement this project using the Java language.
Steps for Autosizing TextView
In this article, the dial pad is taken as an example. This method can be used in building the calculator and can be used in many other scenarios where the TextView resize is required.
Step 1: Create an android studio project with an empty activity
- You may refer to this Android | How to Create/Start a New Project in Android Studio on how to create an empty activity android studio project.
- Rename the application name as Auto resize TextView, and let the name of the layout be activity_main.xml
- And select Java as Language.
Step 2: Building an appropriate layout by working with the activity_main.xml file
- As we have taken the dial pad as an example to demonstrate the auto-resizing of the TextView, so invoke the following code in the activity_main.xml file to make the UI like a dial pad.
- One can see attributes of TextView in above code app:autoSizeMaxTextSize=”80sp”, this is the initial sizes of TextView.
- app:autoSizeMinTextSize=”10sp” using this attribute the TextView will be resized up to the size of 10sp and app:autoSizeStepGranularity=”2sp” using this attribute we are uniformly reducing the size of the TextView as 2sp when it goes out of the screen.
- app:autoSizeTextType=”uniform” by using this attribute we are simply resizing the TextView uniformly.
- One thing to remember is one shouldn’t set the height and width of the TextView as wrap_content.
- To disable the resizing of the TextView, can set this attribute to none. As you can see below.
The following Output UI is produced:
Step 3: Now handling each Button separately, using the onClick XML attribute
- Now in the MainActivity.java file, we will handle all the onClick functions of each Button separately, and set the TextView to the appropriate number when pressed. So, now invoke the following code: