热门标签 | HotTags
当前位置:  开发笔记 > Android > 正文

Android实现树形层级ListView

这篇文章主要介绍了Android实现树形层级ListView的相关资料,需要的朋友可以参考下

直接贴代码,代码中有相应注释:

主界面Activity,布局就只一个ListView:

public class MainActivity extends Activity {
private ListView mListView;
private TreeListViewAdapter mAdapter;
private List mDatas = new ArrayList();

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.mListView = (ListView) findViewById(R.id.listview);
initTestDatas();
try {
mAdapter = new TreeListViewAdapter(mListView, this, mDatas, 0);
}
catch (Exception e) {
e.printStackTrace();
}
this.mListView.setAdapter(mAdapter);
mAdapter.setmTreeListener(new TreeViewOnItemClick() {


@Override
public void onTreeItemClick(int position, Node node) {
Toast.makeText(MainActivity.this, "你点击的是:" + node.getName(), Toast.LENGTH_SHORT).show();
}
});
this.mListView.setOnItemLongClickListener(new OnItemLongClickListener() {


@Override
public boolean onItemLongClick(AdapterView<&#63;> arg0, View arg1, final int arg2, long arg3) {
final EditText edt = new EditText(MainActivity.this);
new AlertDialog.Builder(MainActivity.this).setTitle("Insert").setView(edt).setPositiveButton("submit", new OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
if (TextUtils.isEmpty(edt.getText().toString())) {
Toast.makeText(MainActivity.this, "请填写添加内容", Toast.LENGTH_SHORT).show();
}
else {
mAdapter.insertNodeData(arg2, edt.getText().toString());
}
}
}).setNegativeButton("Cancel", null).create().show();
return true;
}
});
}


private void initTestDatas() {
TestBean bean = null;
bean = new TestBean(1, 0, "文件目录1");
mDatas.add(bean);
bean = new TestBean(2, 0, "文件目录2");
mDatas.add(bean);
bean = new TestBean(3, 0, "文件目录3");
mDatas.add(bean);
bean = new TestBean(4, 1, "文件目录4");
mDatas.add(bean);
bean = new TestBean(5, 1, "文件目录5");
mDatas.add(bean);
bean = new TestBean(6, 2, "文件目录6");
mDatas.add(bean);
bean = new TestBean(7, 2, "文件目录7");
mDatas.add(bean);
bean = new TestBean(8, 3, "文件目录8");
mDatas.add(bean);
bean = new TestBean(9, 3, "文件目录9");
mDatas.add(bean);
bean = new TestBean(10, 0, "文件目录10");
mDatas.add(bean);
}
}

数据适配器基类:

**
 * 树形ListView的数据适配器类
 * @description:
 * @author ldm
 * @date 2015-10-9 上午9:47:01
 */
public abstract class TreeViewBaseAdapter extends BaseAdapter {
protected Context context;
protected List datas;
protected List mAllNodes;
protected List mVisibleNodes;
protected LayoutInflater mInflater;
protected ListView treeLv;
protected TreeViewOnItemClick mTreeListener;


public TreeViewBaseAdapter(ListView treeLv, Context context, List datas, int defaultExpandLevel) throws IllegalAccessException, IllegalArgumentException {
this.cOntext= context;
this.treeLv = treeLv;
mInflater = LayoutInflater.from(context);
mAllNodes = TreeHelperTools.getSortedNodes(datas, defaultExpandLevel);
mVisibleNodes = TreeHelperTools.filterVisibleNodes(mAllNodes);
this.treeLv.setOnItemClickListener(new OnItemClickListener() {


@Override
public void onItemClick(AdapterView<&#63;> arg0, View arg1, int position, long arg3) {
expandOrCollapse(position);
if(mTreeListener!=null){
mTreeListener.onTreeItemClick(position, mVisibleNodes.get(position));
}
}
});
}


public void setmTreeListener(TreeViewOnItemClick mTreeListener) {
this.mTreeListener = mTreeListener;
}


/**
* 设置ListView点击item节点时,是否应该展开
* @description:
* @author ldm
* @date 2015-10-10 上午9:05:08
*/
protected void expandOrCollapse(int position) {
Node n=mVisibleNodes.get(position);
if(n!=null){
if(n.isLeaf()){
return;
}
n.setExpand(!n.isExpand());
mVisibleNodes=TreeHelperTools.filterVisibleNodes(mAllNodes);
notifyDataSetChanged();
}
}


@Override
public int getCount() {
// TODO Auto-generated method stub
return mVisibleNodes.size();
}


@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return mVisibleNodes.get(position);
}


@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}


@Override
public View getView(int position, View convertView, ViewGroup parent) {
Node node=mVisibleNodes.get(position);
cOnvertView= getContentView(node,position, convertView, parent);
return convertView;
}


public abstract View getContentView(Node node,int position, View convertView, ViewGroup parent);
public interface TreeViewOnItemClick{
void onTreeItemClick(int position,Node node);
}
}

我们使用的Adapter

 public class TreeListViewAdapter extends TreeViewBaseAdapter {


public TreeListViewAdapter(ListView treeLv, Context context, List datas, int defaultExpandLevel) throws IllegalAccessException, IllegalArgumentException {
super(treeLv, context, datas, defaultExpandLevel);
}


@Override
public View getContentView(Node node, int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (cOnvertView== null) {
holder = new ViewHolder();
cOnvertView= mInflater.inflate(R.layout.tree_listview_item, parent, false);
holder.mItemIv = (ImageView) convertView.findViewById(R.id.mItemIv);
holder.mItemTv = (TextView) convertView.findViewById(R.id.mItemTv);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.mItemIv.setPadding(node.getLevel()*30, 3, 3, 3);
if (node.getIcon() == -1) {
holder.mItemIv.setVisibility(View.INVISIBLE);
}
else {
holder.mItemIv.setVisibility(View.VISIBLE);
holder.mItemIv.setImageResource(node.getIcon());
}
holder.mItemTv.setText(node.getName());
return convertView;
}


private static class ViewHolder {
ImageView mItemIv;
TextView mItemTv;
}


/**
* 动态插入数据
* @description:
* @author ldm
* @date 2015-10-10 上午10:08:03
*/
public void insertNodeData(int position,String label) {
Node node=mVisibleNodes.get(position);
int indexOf=mAllNodes.indexOf(node);
Node insertNode=new Node(-1, node.getId(), label);
insertNode.setParent(node);
node.getChildren().add(insertNode);
mAllNodes.add(indexOf+1,insertNode);
mVisibleNodes=TreeHelperTools.filterVisibleNodes(mVisibleNodes);
notifyDataSetChanged();
}
}

数据处理的工具类:

public class TreeDatasHelperTools {
/**
* 将用户提供的数据转化成树层级上可用数据
* @description:
* @date 2015-10-9 下午4:07:24
*/
public static  List datas2Nodes(List datas) throws IllegalAccessException, IllegalArgumentException {
List nodes = new ArrayList();
Node node = null;
for (T t : datas) {
int id = -1;
int pid = -1;
String label = "";
// node = new Node();
Class clazz = t.getClass();
Field[] fields = clazz.getDeclaredFields();// 反射获取类中的字段
for (Field field : fields) {
if (field.getAnnotation(TreeNodeId.class) != null) {// 根据字段上的注解来获取对应的值
field.setAccessible(true);// 在java的反射使用中,如果字段是私有的,那么必须要对这个字段设置才能正常使用,否则报错
id = field.getInt(t);
}
if (field.getAnnotation(TreeNodePid.class) != null) {
field.setAccessible(true);
pid = field.getInt(t);
}
if (field.getAnnotation(TreeNodeLabel.class) != null) {
field.setAccessible(true);
label = (String) field.get(t);
}
}
node = new Node(id, pid, label);
nodes.add(node);


}
// 设置nodes中的父子节点关系
for (int i = 0; i  0 && n.isExpand()) {// 如果有子节点且展开状态
n.setIcon(R.drawable.icon_unable);
}
else if (n.getChildren().size() > 0 && !n.isExpand()) {
n.setIcon(R.drawable.icon_enable);
}
else {
n.setIcon(-1);
}
}


public static  List getSortedNodes(List datas, int defaultExpandLevel) throws IllegalAccessException, IllegalArgumentException {
List result = new ArrayList();
List nodes = datas2Nodes(datas);
// 首先获取根节点数据
List rootNodes = getRootNodes(nodes);
for (Node node : rootNodes) {
addNode(result, node, defaultExpandLevel, 1);
}
return result;


}



/**
* 获取数据中的所有根节点数据
* @description:
* @date 2015-10-9 下午5:00:32
*/
private static List getRootNodes(List nodes) {
List root = new ArrayList();
for (Node node : nodes) {
if (node.isRoot()) {
root.add(node);
}
}
return root;
}


/**
* 获取到可见的节点数据
* @description:
* @date 2015-10-9 下午5:12:58
*/
public static List filterVisibleNodes(List mAllNodes) {
List nodes = new ArrayList();
for (Node node : mAllNodes) {
if (node.isRoot() || node.isParentExpand()) {
setNodeIcon(node);
nodes.add(node);
}
}
return nodes;
}


/**
* 把一个节点的所有子节点都放入result中
* @description:
* @date 2015-10-9 下午5:05:57
*/
private static void addNode(List result, Node node, int defaultExpandLevel, int currentLevel) {
result.add(node);
if (defaultExpandLevel >= currentLevel) {
node.setExpand(true);
}
if (node.isLeaf()) { return; }
for (int i = 0; i 

数据实体Bean:

public class TestBean {
@TreeNodeId
private int id;//添加对应的注解
@TreeNodePid
private int pid;
@TreeNodeLabel
private String label;
private String desc;


public TestBean(int id, int pid, String label) {
super();
this.id = id;
this.pid = pid;
this.label = label;
}


public TestBean() {
// TODO Auto-generated constructor stub
}


public int getId() {
return id;
}


public void setId(int id) {
this.id = id;
}


public int getPid() {
return pid;
}


public void setPid(int pid) {
this.pid = pid;
}


public String getLabel() {
return label;
}


public void setLabel(String label) {
this.label = label;
}


public String getDesc() {
return desc;
}


public void setDesc(String desc) {
this.desc = desc;
}

}

数据展示中的Node类,我们可以通过反射+注解把任意实体bean如TestBean映射成我们想要的Node

public class Node {
private int id;// 所在节点id
private int pid = 0;// 父节点的id
private String name;// 对应的内容
private int level;// 所在ListView中树层级
private boolean isExpand = false;// 所在节点是否展开
private int icon;// 图标icon
private Node parent;// 父节点Node
private List children = new ArrayList();// 对应的子节点数据集
public Node() {
}

public Node(int id, int pid, String name) {
this.id = id;
this.pid = pid;
this.name = name;
}


public int getId() {
return id;
}


public void setId(int id) {
this.id = id;
}


public int getPid() {
return pid;
}


public void setPid(int pid) {
this.pid = pid;
}


public String getName() {
return name;
}


public void setName(String name) {
this.name = name;
}

/**
* 当前节点所在的层级
* @description:
* @date 2015-10-9 下午4:02:29
*/
public int getLevel() {
return parent == null &#63; 0 : parent.getLevel() + 1;
}


public void setLevel(int level) {
this.level = level;
}


public boolean isExpand() {
return isExpand;
}


public void setExpand(boolean isExpand) {
this.isExpand = isExpand;
if (!isExpand && children.size() > 0) {// 如果当前节点没有展开,则其子节点展开状态也是:没展开
for (Node node : children) {
node.setExpand(false);
}
}
}


public int getIcon() {
return icon;
}


public void setIcon(int icon) {
this.icon = icon;
}


public Node getParent() {
return parent;
}


public void setParent(Node parent) {
this.parent = parent;
}


public List getChildren() {
return children;
}


public void setChildren(List children) {
this.children = children;
}


/**
* 判断当前节点有没有子节点
* @description:
* @author ldm
* @date 2015-10-9 下午3:59:42
*/
public boolean isLeaf() {
return children.size() == 0;
}


/**
* 是不是根节点
* @description:
* @author ldm
* @date 2015-10-9 下午3:58:15
*/
public boolean isRoot() {
return parent == null;
}


/**
* 当前节点所在父节点是否展开
* @description:
* @author ldm
* @date 2015-10-9 下午3:58:34
*/
public boolean isParentExpand() {
if (parent == null) {
return false;
}
else {
return parent.isExpand;
}
}
}

用到的注解类:

@Target(ElementType.FIELD)//定义注解的作用目标:字段、枚举的常量
@Retention(RetentionPolicy.RUNTIME)//注解策略: 注解会在class字节码文件中存在,在运行时可以通过反射获取到
public @interface TreeNodeId {
}
@Target(ElementType.FIELD)//定义注解的作用目标:字段、枚举的常量
@Retention(RetentionPolicy.RUNTIME)//注解策略: 注解会在class字节码文件中存在,在运行时可以通过反射获取到
public @interface TreeNodeLabel {
}
``
@Target(ElementType.FIELD)//定义注解的作用目标:字段、枚举的常量 
@Retention(RetentionPolicy.RUNTIME)//注解策略: 注解会在class字节码文件中存在,在运行时可以通过反射获取到 
public @interface TreeNodePid { 
}

以上就是Android实现树形层级ListView的相关代码,希望对大家的学习有所帮助。


推荐阅读
  • 国内BI工具迎战国际巨头Tableau,稳步崛起
    尽管商业智能(BI)工具在中国的普及程度尚不及国际市场,但近年来,随着本土企业的持续创新和市场推广,国内主流BI工具正逐渐崭露头角。面对国际品牌如Tableau的强大竞争,国内BI工具通过不断优化产品和技术,赢得了越来越多用户的认可。 ... [详细]
  • 优化ListView性能
    本文深入探讨了如何通过多种技术手段优化ListView的性能,包括视图复用、ViewHolder模式、分批加载数据、图片优化及内存管理等。这些方法能够显著提升应用的响应速度和用户体验。 ... [详细]
  • 本文将详细介绍如何使用剪映应用中的镜像功能,帮助用户轻松实现视频的镜像效果。通过简单的步骤,您可以快速掌握这一实用技巧。 ... [详细]
  • 深入理解Cookie与Session会话管理
    本文详细介绍了如何通过HTTP响应和请求处理浏览器的Cookie信息,以及如何创建、设置和管理Cookie。同时探讨了会话跟踪技术中的Session机制,解释其原理及应用场景。 ... [详细]
  • 本文介绍如何在 Xcode 中使用快捷键和菜单命令对多行代码进行缩进,包括右缩进和左缩进的具体操作方法。 ... [详细]
  • 本文介绍了一款用于自动化部署 Linux 服务的 Bash 脚本。该脚本不仅涵盖了基本的文件复制和目录创建,还处理了系统服务的配置和启动,确保在多种 Linux 发行版上都能顺利运行。 ... [详细]
  • 在Linux系统中配置并启动ActiveMQ
    本文详细介绍了如何在Linux环境中安装和配置ActiveMQ,包括端口开放及防火墙设置。通过本文,您可以掌握完整的ActiveMQ部署流程,确保其在网络环境中正常运行。 ... [详细]
  • Android 渐变圆环加载控件实现
    本文介绍了如何在 Android 中创建一个自定义的渐变圆环加载控件,该控件已在多个知名应用中使用。我们将详细探讨其工作原理和实现方法。 ... [详细]
  • 如何在WPS Office for Mac中调整Word文档的文字排列方向
    本文将详细介绍如何使用最新版WPS Office for Mac调整Word文档中的文字排列方向。通过这些步骤,用户可以轻松更改文本的水平或垂直排列方式,以满足不同的排版需求。 ... [详细]
  • 本文总结了在使用Ionic 5进行Android平台APK打包时遇到的问题,特别是针对QRScanner插件的改造。通过详细分析和提供具体的解决方法,帮助开发者顺利打包并优化应用性能。 ... [详细]
  • 理解存储器的层次结构有助于程序员优化程序性能,通过合理安排数据在不同层级的存储位置,提升CPU的数据访问速度。本文详细探讨了静态随机访问存储器(SRAM)和动态随机访问存储器(DRAM)的工作原理及其应用场景,并介绍了存储器模块中的数据存取过程及局部性原理。 ... [详细]
  • 360SRC安全应急响应:从漏洞提交到修复的全过程
    本文详细介绍了360SRC平台处理一起关键安全事件的过程,涵盖从漏洞提交、验证、排查到最终修复的各个环节。通过这一案例,展示了360在安全应急响应方面的专业能力和严谨态度。 ... [详细]
  • 几何画板展示电场线与等势面的交互关系
    几何画板是一款功能强大的物理教学软件,具备丰富的绘图和度量工具。它不仅能够模拟物理实验过程,还能通过定量分析揭示物理现象背后的规律,尤其适用于难以在实际实验中展示的内容。本文将介绍如何使用几何画板演示电场线与等势面之间的关系。 ... [详细]
  • 本文介绍如何通过Windows批处理脚本定期检查并重启Java应用程序,确保其持续稳定运行。脚本每30分钟检查一次,并在需要时重启Java程序。同时,它会将任务结果发送到Redis。 ... [详细]
  • MySQL中枚举类型的所有可能值获取方法
    本文介绍了一种在MySQL数据库中查询枚举(ENUM)类型字段所有可能取值的方法,帮助开发者更好地理解和利用这一数据类型。 ... [详细]
author-avatar
手机用户2502863461
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有