Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile / Android

Tree View in Java For Android

4.89/5 (7 votes)
13 Sep 2016CPOL1 min read 24.9K   510  
Tree View in Swift for Android that is easy to implement and use

Introduction

I love the TreeView in .NET and want one for an Android app, but discovered that Android does not have a TreeView control so after hunting around, I just decided to write one of my own.

Background

I was unable to find any TreeViews at all online, and the closest thing was a 2 level tree with a checkbox, but I did not ever look at it because I did not like it, so this is all my own work.

Using the Code

I did this in Android Studio and started with an empty project. TreeListActivity is the Main Activity and uses tree_view_cell in the Layout directory.

Even zipped, the project is too big to include in the article, so I Zipped the "main" section so you can get the source code and resources.

The data for the Tree is loaded in TreeViewLists.java. It is an ArrayList of a class called TreeViewData. Be sure to use a unique id for each one and then for the children nodes, set the parentId to the id of the node they belong under. Set the zero level parentId to something that is not going to be used.

Java
public static ArrayList<TreeViewData> LoadInitialData()
{
    ArrayList<TreeViewData> data = new ArrayList<TreeViewData>();

    data.add(new TreeViewData(0, "cindy's family tree", "1", "-1"));
    data.add(new TreeViewData(0, "jack's family tree", "2", "-1"));
    data.add(new TreeViewData(1, "katherine", "3",  "1"));
    data.add(new TreeViewData(1, "kyle", "4", "1"));
    data.add(new TreeViewData(2, "hayley","5", "3"));
    data.add(new TreeViewData(2, "macey", "6", "3"));
    data.add(new TreeViewData(1, "katelyn", "7", "2"));
    data.add(new TreeViewData(1, "jared", "8", "2"));
    data.add(new TreeViewData(1, "denyee", "9", "2"));
    data.add(new TreeViewData(2, "cayleb", "10", "4"));
    data.add(new TreeViewData(2, "carter", "11", "4"));
    data.add(new TreeViewData(2, "braylon", "12", "4"));
    data.add(new TreeViewData(3, "samson", "13", "5"));
    data.add(new TreeViewData(3, "samson", "14", "6"));

    return data;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)