ExpandableTextView is an Android library which allows us to easily create a TextView which can expand/collapse when user clicks on it .we can use this feature in many apps such as movie review app or storytelling app and in many other apps. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Before going to the coding section first do some pre-task
Go to app -> res -> values -> colors.xml file and set the colors for the app.
Go to app -> res -> values -> strings.xml file and set the string for the app.
Go to Gradle Scripts -> build.gradle (Module: app) section and import the following dependencies and click the “sync Now” on the above pop-up.
Step 3: Designing the UI
In the activity_main.xml remove the default TextView and change the layout to RelativeLayout and add the ExpandableTextView and inside it, we add a TextView and ImageButton as shown below. 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.
Note: The id of ImageButton must be expanded collapse and id of TextView must be expandable text
Properties of ExpandableTextView
- expandableTextView:collapseDrawable: Customize a drawable set to ImageButton to collapse the TextView
- expandableTextView:expandDrawable: It is used to set drawable to ImageButton to expand the TextView
- expandableTextView:maxCollapsedLines: The maximum number of text lines allowed to be shown when the TextView gets collapsed (defaults value is 8 )
- expandableTextView:animDuration: It is used to set the duration of the Animation for the expansion/collapse (defaults to 300ms)
- expandableTextView:animAlphaStart: The alpha value of the TextView when the animation starts (NOTE) Set this value to 1 if you want to disable the alpha animation (defaults to 0.7f )
Step 4: Coding Part
Open the MainActivity.java file and inside on Create() create and initialize the expandable text view and setText to it from the strings.xml (R.string.expandable_text) as shown below
Below is the complete code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.