TreeView in Android with Example
If you are looking for the new UI designs for the representation of huge data, then there are so many ways for the representation of this type of data. You can use pie charts, graphs, and many more view types for the implementation of these views. For displaying such huge data then we can prefer using a TreeView. TreeView is similar to that of a tree in which it is having a parent node and inside that parent node, you can create multiple nodes according to requirement. In this example, we can take a look at creating a TreeView in your Android application. Now we will move towards the implementation of Tree View. Note that we are going to implement this project using the Java language.
What is TreeView and How it looks?
TreeView is a pattern for the representation of data in the form of the tree so that it becomes easier for users to understand the organization of data in our app. A sample image is given below to get an idea of how TreeView looks like.
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: Add dependency to build.gradle(Module:app)
Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section.
After adding this dependency sync your project and now we will move towards its implementation.
Step 3: Modify the strings.xml file
Below is the code for the strings.xml file.
Step 4: 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.
Step 5: Create a new XML file
After adding this TreeView create a new XML file for your node which we have to display inside our TreeView. For creating a new XML file navigate to the app > res > layout > Right-click > New > Layout Resource file. Give a name to your file (Here we have given tree_view_node) and click on create. After creating this file add the below code to it. Below is the code for the tree_view_node.xml file.
Step 6: Create a new Java class
Now create a new Java class as View Holder for handling our nodes in Tree View. To create a new java class please refer to the How to Create Classes in Android Studio. After creating a new java class add the below code to it. Here we have named the class as Viewholder. Below is the code for the Viewholder.java file.
After creating the Viewholder class then we will move towards the implementation of TreeView in our MainActivity.java file.
Step 7: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.