您好,登錄后才能下訂單哦!
這篇文章主要介紹Android如何實現多級樹形選擇列表,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
項目中有多個地方要用到多級列表的菜單,最開始我用的是ExpandableListView,但問題是ExpandableListView只支持兩級列表,于是我就用ExpandableListView嵌套ExpandableListView,但非常麻煩,而且關鍵的是具體分幾級是不確定的,也就是可能一級,可能多級,這要是五六級嵌套ListView,于是我就去學習鴻洋大神之前寫的一篇關于實現Android多級樹形列表的文章,實現很巧妙,使用一個ListView就可以實現多級列表效果,我做了部分修改,功能順利實現。
1.定義節點實體類:
package com.xiaoyehai.multileveltreelist.treelist; import java.util.ArrayList; import java.util.List; /** * 節點實體類 * Created by xiaoyehai on 2018/7/11 0011. */ public class Node<T> { /** * 當前節點id */ private String id; /** * 父節點id */ private String pid; /** * 節點數據實體類 */ private T data; /** * 設置開啟 關閉的圖片 */ public int iconExpand = -1, iconNoExpand = -1; /** * 節點名稱 */ private String name; /** * 當前的級別 */ private int level; /** * 是否展開 */ private boolean isExpand = false; private int icon = -1; /** * 下一級的子Node */ private List<Node> children = new ArrayList<>(); /** * 父Node */ private Node parent; /** * 是否被checked選中 */ private boolean isChecked; public Node() { } public Node(String id, String pid, String name) { this.id = id; this.pid = pid; this.name = name; } public Node(String id, String pid, T data, String name) { this.id = id; this.pid = pid; this.data = data; this.name = name; } /** * 是否為根節點 * * @return */ public boolean isRootNode() { return parent == null; } /** * 判斷父節點是否展開 * * @return */ public boolean isParentExpand() { if (parent == null) return false; return parent.isExpand(); } /** * 是否是葉子節點 * * @return */ public boolean isLeaf() { return children.size() == 0; } /** * 獲取當前的級別level */ public int getLevel() { return parent == null ? 0 : parent.getLevel() + 1; } /** * 設置展開 * * @param isExpand */ public void setExpand(boolean isExpand) { this.isExpand = isExpand; if (!isExpand) { for (Node node : children) { node.setExpand(isExpand); } } } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPid() { return pid; } public void setPid(String pid) { this.pid = pid; } public T getData() { return data; } public void setData(T data) { this.data = data; } public int getIconExpand() { return iconExpand; } public void setIconExpand(int iconExpand) { this.iconExpand = iconExpand; } public int getIconNoExpand() { return iconNoExpand; } public void setIconNoExpand(int iconNoExpand) { this.iconNoExpand = iconNoExpand; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void setLevel(int level) { this.level = level; } public boolean isExpand() { return isExpand; } public int getIcon() { return icon; } public void setIcon(int icon) { this.icon = icon; } public List<Node> getChildren() { return children; } public void setChildren(List<Node> children) { this.children = children; } public Node getParent() { return parent; } public void setParent(Node parent) { this.parent = parent; } public boolean isChecked() { return isChecked; } public void setChecked(boolean checked) { isChecked = checked; } }
2.定義每個節點數據的實體類
因為項目中多個地方用到樹形菜單,而且數據都不一樣,每個節點數據都比較復雜,所以我單獨封裝出一個類,要是數據和簡單,這步可以不用,直接用Node類。
例如:
/** * 每個節點的具體數據 * Created by xiaoyehai on 2018/7/11 0011. */ public class NodeData { private String name; public NodeData() { } public NodeData(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
3.TreeHelper
package com.xiaoyehai.multileveltreelist.treelist; import java.util.ArrayList; import java.util.List; /** * Created by xiaoyehai on 2018/7/11 0011. */ public class TreeHelper { /** * 傳入node 返回排序后的Node * 拿到用戶傳入的數據,轉化為List<Node>以及設置Node間關系,然后根節點,從根往下遍歷進行排序; * * @param datas * @param defaultExpandLevel 默認顯示 * @return * @throws IllegalArgumentException * @throws IllegalAccessException */ public static List<Node> getSortedNodes(List<Node> datas, int defaultExpandLevel) { List<Node> result = new ArrayList<Node>(); // 設置Node間父子關系 List<Node> nodes = convetData2Node(datas); // 拿到根節點 List<Node> rootNodes = getRootNodes(nodes); // 排序以及設置Node間關系 for (Node node : rootNodes) { addNode(result, node, defaultExpandLevel, 1); } return result; } /** * 過濾出所有可見的Node * 過濾Node的代碼很簡單,遍歷所有的Node,只要是根節點或者父節點是展開狀態就添加返回 * * @param nodes * @return */ public static List<Node> filterVisibleNode(List<Node> nodes) { List<Node> result = new ArrayList<Node>(); for (Node node : nodes) { // 如果為跟節點,或者上層目錄為展開狀態 if (node.isRootNode() || node.isParentExpand()) { setNodeIcon(node); result.add(node); } } return result; } /** * 將我們的數據轉化為樹的節點 * 設置Node間,父子關系;讓每兩個節點都比較一次,即可設置其中的關系 */ private static List<Node> convetData2Node(List<Node> nodes) { for (int i = 0; i < nodes.size(); i++) { Node n = nodes.get(i); for (int j = i + 1; j < nodes.size(); j++) { Node m = nodes.get(j); if (m.getPid() instanceof String) { if (m.getPid().equals(n.getId())) { //n時m的父節點 n.getChildren().add(m); m.setParent(n); } else if (m.getId().equals(n.getPid())) { //m時n的父節點 m.getChildren().add(n); n.setParent(m); } } else { if (m.getPid() == n.getId()) { n.getChildren().add(m); m.setParent(n); } else if (m.getId() == n.getPid()) { m.getChildren().add(n); n.setParent(m); } } } } return nodes; } /** * 獲得根節點 * * @param nodes * @return */ private static List<Node> getRootNodes(List<Node> nodes) { List<Node> root = new ArrayList<Node>(); for (Node node : nodes) { if (node.isRootNode()) root.add(node); } return root; } /** * 把一個節點上的所有的內容都掛上去 * 通過遞歸的方式,把一個節點上的所有的子節點等都按順序放入 */ private static <T> void addNode(List<Node> nodes, Node<T> node, int defaultExpandLeval, int currentLevel) { nodes.add(node); if (defaultExpandLeval >= currentLevel) { node.setExpand(true); } if (node.isLeaf()) return; for (int i = 0; i < node.getChildren().size(); i++) { addNode(nodes, node.getChildren().get(i), defaultExpandLeval, currentLevel + 1); } } /** * 設置節點的圖標 * * @param node */ private static void setNodeIcon(Node node) { if (node.getChildren().size() > 0 && node.isExpand()) { node.setIcon(node.iconExpand); } else if (node.getChildren().size() > 0 && !node.isExpand()) { node.setIcon(node.iconNoExpand); } else { node.setIcon(-1); } } }
4.TreeListViewAdapter
對于ListView的適配器,需要繼承自TreeListViewAdapter,如
package com.xiaoyehai.multileveltreelist.treelist; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.ListView; import java.util.ArrayList; import java.util.List; /** * Created by xiaoyehai on 2018/7/11 0011. */ public abstract class TreeListViewAdapter extends BaseAdapter { protected Context mContext; /** * 默認不展開 */ private int defaultExpandLevel = 0; /** * 展開與關閉的圖片 */ private int iconExpand = -1, iconNoExpand = -1; /** * 存儲所有的Node */ protected List<Node> mAllNodes = new ArrayList<>(); protected LayoutInflater mInflater; /** * 存儲所有可見的Node */ protected List<Node> mNodes = new ArrayList<>(); /** * 點擊的回調接口 */ private OnTreeNodeClickListener onTreeNodeClickListener; public void setOnTreeNodeClickListener(OnTreeNodeClickListener onTreeNodeClickListener) { this.onTreeNodeClickListener = onTreeNodeClickListener; } public TreeListViewAdapter(ListView listView, Context context, List<Node> datas, int defaultExpandLevel, int iconExpand, int iconNoExpand) { this.mContext = context; this.defaultExpandLevel = defaultExpandLevel; this.iconExpand = iconExpand; this.iconNoExpand = iconNoExpand; for (Node node : datas) { node.getChildren().clear(); node.setIconExpand(iconExpand); node.setIconNoExpand(iconNoExpand); } /** * 對所有的Node進行排序 */ mAllNodes = TreeHelper.getSortedNodes(datas, defaultExpandLevel); /** * 過濾出可見的Node */ mNodes = TreeHelper.filterVisibleNode(mAllNodes); mInflater = LayoutInflater.from(context); /** * 設置節點點擊時,可以展開以及關閉;并且將ItemClick事件繼續往外公布 */ listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { expandOrCollapse(position); if (onTreeNodeClickListener != null) { onTreeNodeClickListener.onClick(mNodes.get(position), position); } } }); } /** * @param listView * @param context * @param datas * @param defaultExpandLevel 默認展開幾級樹 */ public TreeListViewAdapter(ListView listView, Context context, List<Node> datas, int defaultExpandLevel) { this(listView, context, datas, defaultExpandLevel, -1, -1); } /** * 相應ListView的點擊事件 展開或關閉某節點 * * @param position */ public void expandOrCollapse(int position) { Node n = mNodes.get(position); if (n != null) {// 排除傳入參數錯誤異常 if (!n.isLeaf()) { n.setExpand(!n.isExpand()); //獲取所有可見的Node mNodes = TreeHelper.filterVisibleNode(mAllNodes); notifyDataSetChanged();// 刷新視圖 } } } @Override public int getCount() { return mNodes.size(); } @Override public Object getItem(int position) { return mNodes.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { Node node = mNodes.get(position); convertView = getConvertView(node, position, convertView, parent); // 設置內邊距 convertView.setPadding(node.getLevel() * 50, 12, 12, 12); return convertView; } /** * 獲取排序后所有節點 * * @return */ public List<Node> getAllNodes() { if (mAllNodes == null) mAllNodes = new ArrayList<Node>(); return mAllNodes; } /** * 獲取所有選中節點 * * @return */ public List<Node> getSelectedNode() { List<Node> checks = new ArrayList<Node>(); for (int i = 0; i < mAllNodes.size(); i++) { Node n = mAllNodes.get(i); if (n.isChecked()) { checks.add(n); } } return checks; } /** * 設置多選 * * @param node * @param checked */ protected void setChecked(final Node node, boolean checked) { node.setChecked(checked); setChildChecked(node, checked); if (node.getParent() != null) setNodeParentChecked(node.getParent(), checked); notifyDataSetChanged(); } /** * 設置是否選中 * * @param node * @param checked */ public <T> void setChildChecked(Node<T> node, boolean checked) { if (!node.isLeaf()) { node.setChecked(checked); for (Node childrenNode : node.getChildren()) { setChildChecked(childrenNode, checked); } } else { node.setChecked(checked); } } private void setNodeParentChecked(Node node, boolean checked) { if (checked) { node.setChecked(checked); if (node.getParent() != null) setNodeParentChecked(node.getParent(), checked); } else { List<Node> childrens = node.getChildren(); boolean isChecked = false; for (Node children : childrens) { if (children.isChecked()) { isChecked = true; } } //如果所有自節點都沒有被選中 父節點也不選中 if (!isChecked) { node.setChecked(checked); } if (node.getParent() != null) setNodeParentChecked(node.getParent(), checked); } } /** * 清除掉之前數據并刷新 重新添加 * * @param mlists * @param defaultExpandLevel 默認展開幾級列表 */ public void addDataAll(List<Node> mlists, int defaultExpandLevel) { mAllNodes.clear(); addData(-1, mlists, defaultExpandLevel); } /** * 在指定位置添加數據并刷新 可指定刷新后顯示層級 * * @param index * @param mlists * @param defaultExpandLevel 默認展開幾級列表 */ public void addData(int index, List<Node> mlists, int defaultExpandLevel) { this.defaultExpandLevel = defaultExpandLevel; notifyData(index, mlists); } /** * 在指定位置添加數據并刷新 * * @param index * @param mlists */ public void addData(int index, List<Node> mlists) { notifyData(index, mlists); } /** * 添加數據并刷新 * * @param mlists */ public void addData(List<Node> mlists) { addData(mlists, defaultExpandLevel); } /** * 添加數據并刷新 可指定刷新后顯示層級 * * @param mlists * @param defaultExpandLevel */ public void addData(List<Node> mlists, int defaultExpandLevel) { this.defaultExpandLevel = defaultExpandLevel; notifyData(-1, mlists); } /** * 添加數據并刷新 * * @param node */ public void addData(Node node) { addData(node, defaultExpandLevel); } /** * 添加數據并刷新 可指定刷新后顯示層級 * * @param node * @param defaultExpandLevel */ public void addData(Node node, int defaultExpandLevel) { List<Node> nodes = new ArrayList<>(); nodes.add(node); this.defaultExpandLevel = defaultExpandLevel; notifyData(-1, nodes); } /** * 刷新數據 * * @param index * @param mListNodes */ public void notifyData(int index, List<Node> mListNodes) { for (int i = 0; i < mListNodes.size(); i++) { Node node = mListNodes.get(i); node.getChildren().clear(); node.iconExpand = iconExpand; node.iconNoExpand = iconNoExpand; } for (int i = 0; i < mAllNodes.size(); i++) { Node node = mAllNodes.get(i); node.getChildren().clear(); //node.isNewAdd = false; } if (index != -1) { mAllNodes.addAll(index, mListNodes); } else { mAllNodes.addAll(mListNodes); } /** * 對所有的Node進行排序 */ mAllNodes = TreeHelper.getSortedNodes(mAllNodes, defaultExpandLevel); /** * 過濾出可見的Node */ mNodes = TreeHelper.filterVisibleNode(mAllNodes); //刷新數據 notifyDataSetChanged(); } public abstract View getConvertView(Node node, int position, View convertView, ViewGroup parent); }
5.接口回調:
選中狀態改變的回調:
package com.xiaoyehai.multileveltreelist.treelist; /** * Created by xiaoyehai on 2018/7/12 0012. */ public interface OnTreeNodeCheckedChangeListener { void onCheckChange(Node node, int position, boolean isChecked); }
條目點擊的回調:
package com.xiaoyehai.multileveltreelist.treelist; /** * Created by xiaoyehai on 2018-07-12. */ public interface OnTreeNodeClickListener { void onClick(Node node, int position); }
6.使用:
布局文件:
<ListView android:id="@+id/listview" android:layout_width="match_parent" android:layout_height="match_parent"></ListView>
Activity:
public class ListViewActivity extends AppCompatActivity { private ListView mListView; private List<Node> dataList = new ArrayList<>(); private ListViewAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list_view); mListView = (ListView) findViewById(R.id.listview); initData(); //第一個參數 ListView //第二個參數 上下文 //第三個參數 數據集 //第四個參數 默認展開層級數 0為不展開 //第五個參數 展開的圖標 //第六個參數 閉合的圖標 mAdapter = new ListViewAdapter(mListView, this, dataList, 0, R.drawable.zoomout_yzs, R.drawable.zoomin_yzs); mListView.setAdapter(mAdapter); //獲取所有節點 final List<Node> allNodes = mAdapter.getAllNodes(); for (Node allNode : allNodes) { //Log.e("xyh", "onCreate: " + allNode.getName()); } //選中狀態監聽 mAdapter.setCheckedChangeListener(new OnTreeNodeCheckedChangeListener() { @Override public void onCheckChange(Node node, int position, boolean isChecked) { //獲取所有選中節點 List<Node> selectedNode = mAdapter.getSelectedNode(); for (Node n : selectedNode) { Log.e("xyh", "onCheckChange: " + n.getName()); } } }); } /** * 模擬數據,實際開發中對返回的json數據進行封裝 */ private void initData() { //根節點 Node<NodeData> node = new Node<>("0", "-1", "根節點1"); dataList.add(node); dataList.add(new Node<>("1", "-1", "根節點2")); dataList.add(new Node<>("2", "-1", "根節點3")); //根節點1的二級節點 dataList.add(new Node<>("3", "0", "二級節點")); dataList.add(new Node<>("4", "0", "二級節點")); dataList.add(new Node<>("5", "0", "二級節點")); //根節點2的二級節點 dataList.add(new Node<>("6", "1", "二級節點")); dataList.add(new Node<>("7", "1", "二級節點")); dataList.add(new Node<>("8", "1", "二級節點")); //根節點3的二級節點 dataList.add(new Node<>("9", "2", "二級節點")); dataList.add(new Node<>("10", "2", "二級節點")); dataList.add(new Node<>("11", "2", "二級節點")); //三級節點 dataList.add(new Node<>("12", "3", "三級節點")); dataList.add(new Node<>("13", "3", "三級節點")); dataList.add(new Node<>("14", "3", "三級節點")); dataList.add(new Node<>("15", "4", "三級節點")); dataList.add(new Node<>("16", "4", "三級節點")); dataList.add(new Node<>("17", "4", "三級節點")); dataList.add(new Node<>("18", "5", "三級節點")); dataList.add(new Node<>("19", "5", "三級節點")); dataList.add(new Node<>("20", "5", "三級節點")); //四級節點 dataList.add(new Node<>("21", "12", "四級節點")); //... //可以有無線多層級 } }
adapter:
package com.xiaoyehai.multileveltreelist.adapter; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.xiaoyehai.multileveltreelist.R; import com.xiaoyehai.multileveltreelist.treelist.OnTreeNodeCheckedChangeListener; import com.xiaoyehai.multileveltreelist.treelist.TreeListViewAdapter; import com.xiaoyehai.multileveltreelist.treelist.Node; import java.util.List; /** * Created by xiaoyehai on 2018/7/12 0012. */ public class ListViewAdapter extends TreeListViewAdapter { private OnTreeNodeCheckedChangeListener checkedChangeListener; public void setCheckedChangeListener(OnTreeNodeCheckedChangeListener checkedChangeListener) { this.checkedChangeListener = checkedChangeListener; } public ListViewAdapter(ListView listView, Context context, List<Node> datas, int defaultExpandLevel, int iconExpand, int iconNoExpand) { super(listView, context, datas, defaultExpandLevel, iconExpand, iconNoExpand); } @Override public View getConvertView(final Node node, final int position, View convertView, ViewGroup parent) { final ViewHolder holder; if (convertView == null) { convertView = View.inflate(mContext, R.layout.item, null); holder = new ViewHolder(convertView); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.tvName.setText(node.getName()); if (node.getIcon() == -1) { holder.ivExpand.setVisibility(View.INVISIBLE); } else { holder.ivExpand.setVisibility(View.VISIBLE); holder.ivExpand.setImageResource(node.getIcon()); } holder.checkBox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setChecked(node, holder.checkBox.isChecked()); if (checkedChangeListener != null) { checkedChangeListener.onCheckChange(node, position,holder.checkBox.isChecked()); } } }); if (node.isChecked()) { holder.checkBox.setChecked(true); } else { holder.checkBox.setChecked(false); } return convertView; } static class ViewHolder { private CheckBox checkBox; private TextView tvName; private ImageView ivExpand; public ViewHolder(View convertView) { checkBox = convertView.findViewById(R.id.cb); tvName = convertView.findViewById(R.id.tv_name); ivExpand = convertView.findViewById(R.id.iv_expand); } } }
也可以用RecycleView實現,在我的項目里面都有。
以上是“Android如何實現多級樹形選擇列表”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。