Thursday 15 December 2016

HB Blog 125: AndroidTreeView:- TreeView Implementation For Android.

A Listview is a view that shows items in a vertically scrolling list. The items come from the ListAdapter associated with this view.

An ExpandableListView is a view that shows items in a vertically scrolling two-level list. This differs from the ListView by allowing two levels: groups which can individually be expanded to show its children. The items come from the ExpandableListAdapter associated with this view.
But, we need a view which will not have limit for levels. We can think of a view that presents a hierarchical view of information.

AndroidTreeView is a TreeView implementation for android that has features such as,
    1. N - level expandable/collapsable tree
    2. Custom values, views, styles for nodes
    3. Save state after rotation
    4. Selection mode for nodes
    5. Dynamic add/remove node
Refer the below link for complete sample code:-

Download Sample Code

Have a look on few code snippets,

Integration:-

1) Add library as a dependency to your project
1
compile 'com.github.bmelnychuk:atv:1.2.+'

2) Create your tree starting from root element. TreeNode.root() element will not be displayed so it doesn't require anything to be set.
1
TreeNode root = TreeNode.root();
Create and add your nodes (use your custom object as constructor param)
1
2
3
4
5
 TreeNode parent = new TreeNode("MyParentNode");
 TreeNode child0 = new TreeNode("ChildNode0");
 TreeNode child1 = new TreeNode("ChildNode1");
 parent.addChildren(child0, child1);
 root.addChild(parent);

3) Add tree view to layout
1
2
 AndroidTreeView tView = new AndroidTreeView(getActivity(), root);
 containerView.addView(tView.getView());
The simplest but not styled tree is ready. Now you can see parent node as root of your tree

4) Custom view for nodes
Extend TreeNode.BaseNodeViewHolder and overwrite createNodeView method to prepare custom view for node:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
public class MyHolder extends TreeNode.BaseNodeViewHolder<IconTreeItem> {
    ...
    @Override
    public View createNodeView(TreeNode node, IconTreeItem value) {
        final LayoutInflater inflater = LayoutInflater.from(context);
        final View view = inflater.inflate(R.layout.layout_profile_node, null, false);
        TextView tvValue = (TextView) view.findViewById(R.id.node_value);
        tvValue.setText(value.text);

        return view;
    }
    ...
    public static class IconTreeItem {
        public int icon;
        public String text;
    }
}

5) Connect view holder with node
1
2
 IconTreeItem nodeItem = new IconTreeItem();
  TreeNode child1 = new TreeNode(nodeItem).setViewHolder(new MyHolder(mContext));

6) Consider using
1
2
3
4
TreeNode.setClickListener(TreeNodeClickListener listener);
AndroidTreeView.setDefaultViewHolder
AndroidTreeView.setDefaultNodeClickListener
...

No comments:

Post a Comment