編輯:關於Android編程
我們開發app過程中,經常會碰到需要 多級列表展示的效果。而Android原生sdk中根本沒有3級 4級甚至更多級別的列表控件。
所以我們就要自己去實現一個類似treeListView 的控件,下面這個是我項目中的一個效果圖,可支持多級列表擴展。
android中有ExpandListView控件,但是這個控件只支持兩級列表。對於多級列表如果重寫這個不是很好用。
實現這種列表 思想就是遞歸,構造一個子父級的關系。
話不多說 代碼中體會
Activity
package com.example.customtreeviewdemo; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import com.example.customtreeviewdemo.bean.MyNodeBean; import com.example.customtreeviewdemo.tree.Node; import com.example.customtreeviewdemo.tree.TreeListViewAdapter.OnTreeNodeClickListener; public class MainActivity extends Activity { private ListView treeLv; private Button checkSwitchBtn; private MyTreeListViewAdapter<MyNodeBean> adapter; private List<MyNodeBean> mDatas = new ArrayList<MyNodeBean>(); //標記是顯示Checkbox還是隱藏 private boolean isHide = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initDatas(); treeLv = (ListView) this.findViewById(R.id.tree_lv); checkSwitchBtn = (Button)this.findViewById(R.id.check_switch_btn); checkSwitchBtn.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { if(isHide){ isHide = false; }else{ isHide = true; } adapter.updateView(isHide); } }); try { adapter = new MyTreeListViewAdapter<MyNodeBean>(treeLv, this, mDatas, 10, isHide); adapter.setOnTreeNodeClickListener(new OnTreeNodeClickListener() { @Override public void onClick(Node node, int position) { if (node.isLeaf()) { Toast.makeText(getApplicationContext(), node.getName(), Toast.LENGTH_SHORT).show(); } } @Override public void onCheckChange(Node node, int position, List<Node> checkedNodes) { StringBuffer sb = new StringBuffer(); for (Node n : checkedNodes) { int pos = n.getId() - 1; sb.append(mDatas.get(pos).getName()).append("---") .append(pos + 1).append(";"); } Toast.makeText(getApplicationContext(), sb.toString(), Toast.LENGTH_SHORT).show(); } }); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } treeLv.setAdapter(adapter); } private void initDatas() { mDatas.add(new MyNodeBean(1, 0, "中國古代")); mDatas.add(new MyNodeBean(2, 1, "唐朝")); mDatas.add(new MyNodeBean(3, 1, "宋朝")); mDatas.add(new MyNodeBean(4, 1, "明朝")); mDatas.add(new MyNodeBean(5, 2, "李世民")); mDatas.add(new MyNodeBean(6, 2, "李白")); mDatas.add(new MyNodeBean(7, 3, "趙匡胤")); mDatas.add(new MyNodeBean(8, 3, "蘇轼")); mDatas.add(new MyNodeBean(9, 4, "朱元璋")); mDatas.add(new MyNodeBean(10, 4, "唐伯虎")); mDatas.add(new MyNodeBean(11, 4, "文征明")); mDatas.add(new MyNodeBean(12, 7, "趙建立")); mDatas.add(new MyNodeBean(13, 8, "蘇東東")); mDatas.add(new MyNodeBean(14, 10, "秋香")); } }
Adapter
這個adapter是繼承了自己的定義的一個TreeListViewAdapter,核心實現都是在TreeListViewAdapter這個裡面
package com.example.customtreeviewdemo; import java.util.List; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.example.customtreeviewdemo.tree.Node; import com.example.customtreeviewdemo.tree.TreeListViewAdapter; public class MyTreeListViewAdapter<T> extends TreeListViewAdapter<T> { public MyTreeListViewAdapter(ListView mTree, Context context, List<T> datas, int defaultExpandLevel,boolean isHide) throws IllegalArgumentException, IllegalAccessException { super(mTree, context, datas, defaultExpandLevel,isHide); } @SuppressWarnings("unchecked") @Override public View getConvertView(Node node, int position, View convertView, ViewGroup parent) { ViewHolder viewHolder = null; if (convertView == null) { convertView = mInflater.inflate(R.layout.list_item, parent, false); viewHolder = new ViewHolder(); viewHolder.icon = (ImageView) convertView .findViewById(R.id.id_treenode_icon); viewHolder.label = (TextView) convertView .findViewById(R.id.id_treenode_name); viewHolder.checkBox = (CheckBox)convertView.findViewById(R.id.id_treeNode_check); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } if (node.getIcon() == -1) { viewHolder.icon.setVisibility(View.INVISIBLE); } else { viewHolder.icon.setVisibility(View.VISIBLE); viewHolder.icon.setImageResource(node.getIcon()); } if(node.isHideChecked()){ viewHolder.checkBox.setVisibility(View.GONE); }else{ viewHolder.checkBox.setVisibility(View.VISIBLE); setCheckBoxBg(viewHolder.checkBox,node.isChecked()); } viewHolder.label.setText(node.getName()); return convertView; } private final class ViewHolder { ImageView icon; TextView label; CheckBox checkBox; } /** * checkbox是否顯示 * @param cb * @param isChecked */ private void setCheckBoxBg(CheckBox cb,boolean isChecked){ if(isChecked){ cb.setBackgroundResource(R.drawable.check_box_bg_check); }else{ cb.setBackgroundResource(R.drawable.check_box_bg); } } }
自定義TreeListViewAdapter 這個是整個樹形結構的一個適配器,這裡面主要是實現對Node節點的操作 點擊,選中改變 更新等
package com.example.customtreeviewdemo.tree; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.ListView; import android.widget.RelativeLayout; /** * tree適配器 * @param <T> */ public abstract class TreeListViewAdapter<T> extends BaseAdapter { protected Context mContext; /** * 存儲所有可見的Node */ protected List<Node> mNodes; protected LayoutInflater mInflater; /** * 存儲所有的Node */ protected List<Node> mAllNodes; /** * 點擊的回調接口 */ private OnTreeNodeClickListener onTreeNodeClickListener; public interface OnTreeNodeClickListener { /** * 處理node click事件 * @param node * @param position */ void onClick(Node node, int position); /** * 處理checkbox選擇改變事件 * @param node * @param position * @param checkedNodes */ void onCheckChange(Node node, int position,List<Node> checkedNodes); } public void setOnTreeNodeClickListener( OnTreeNodeClickListener onTreeNodeClickListener) { this.onTreeNodeClickListener = onTreeNodeClickListener; } /** * * @param mTree * @param context * @param datas * @param defaultExpandLevel * 默認展開幾級樹 * @throws IllegalArgumentException * @throws IllegalAccessException */ public TreeListViewAdapter(ListView mTree, Context context, List<T> datas, int defaultExpandLevel, boolean isHide) throws IllegalArgumentException, IllegalAccessException { mContext = context; /** * 對所有的Node進行排序 */ mAllNodes = TreeHelper .getSortedNodes(datas, defaultExpandLevel, isHide); /** * 過濾出可見的Node */ mNodes = TreeHelper.filterVisibleNode(mAllNodes); mInflater = LayoutInflater.from(context); /** * 設置節點點擊時,可以展開以及關閉;並且將ItemClick事件繼續往外公布 */ mTree.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { expandOrCollapse(position); if (onTreeNodeClickListener != null) { onTreeNodeClickListener.onClick(mNodes.get(position), position); } } }); } /** * 相應ListView的點擊事件 展開或關閉某節點 * * @param position */ public void expandOrCollapse(int position) { Node n = mNodes.get(position); if (n != null)// 排除傳入參數錯誤異常 { if (!n.isLeaf()) { n.setExpand(!n.isExpand()); 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(final int position, View convertView, ViewGroup parent) { final Node node = mNodes.get(position); convertView = getConvertView(node, position, convertView, parent); // 設置內邊距 convertView.setPadding(node.getLevel() * 30, 3, 3, 3); if (!node.isHideChecked()) { //獲取各個節點所在的父布局 RelativeLayout myView = (RelativeLayout) convertView; //父布局下的CheckBox CheckBox cb = (CheckBox) myView.getChildAt(1); cb.setOnCheckedChangeListener(new OnCheckedChangeListener(){ @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { TreeHelper.setNodeChecked(node, isChecked); List<Node> checkedNodes = new ArrayList<Node>(); for(Node n:mAllNodes){ if(n.isChecked()){ checkedNodes.add(n); } } onTreeNodeClickListener.onCheckChange(node,position,checkedNodes); TreeListViewAdapter.this.notifyDataSetChanged(); } }); } return convertView; } public abstract View getConvertView(Node node, int position, View convertView, ViewGroup parent); /** * 更新 * @param isHide */ public void updateView(boolean isHide){ for(Node node:mAllNodes){ node.setHideChecked(isHide); } this.notifyDataSetChanged(); } }
node 模型類
package com.example.customtreeviewdemo.bean; public class MyNodeBean { /** * 節點Id */ private int id; /** * 節點父id */ private int pId; /** * 節點name */ private String name; /** * */ private String desc; /** * 節點名字長度 */ private long length; public MyNodeBean(int id, int pId, String name) { super(); 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; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public long getLength() { return length; } public void setLength(long length) { this.length = length; } }
TreeHelper這個也是核心操作類,主要功能是將業務數據和節點數據進行匹配
package com.example.customtreeviewdemo.tree; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import com.example.customtreeviewdemo.R; public class TreeHelper { /** * 根據所有節點獲取可見節點 * * @param allNodes * @return */ public static List<Node> filterVisibleNode(List<Node> allNodes) { List<Node> visibleNodes = new ArrayList<Node>(); for (Node node : allNodes) { // 如果為根節點,或者上層目錄為展開狀態 if (node.isRoot() || node.isParentExpand()) { setNodeIcon(node); visibleNodes.add(node); } } return visibleNodes; } /** * 獲取排序的所有節點 * * @param datas * @param defaultExpandLevel * @return * @throws IllegalArgumentException * @throws IllegalAccessException */ public static <T> List<Node> getSortedNodes(List<T> datas, int defaultExpandLevel, boolean isHide) throws IllegalAccessException, IllegalArgumentException { List<Node> sortedNodes = new ArrayList<Node>(); // 將用戶數據轉化為List<Node> List<Node> nodes = convertData2Nodes(datas, isHide); // 拿到根節點 List<Node> rootNodes = getRootNodes(nodes); // 排序以及設置Node間關系 for (Node node : rootNodes) { addNode(sortedNodes, node, defaultExpandLevel, 1); } return sortedNodes; } /** * 把一個節點上的所有的內容都掛上去 */ private static void addNode(List<Node> nodes, Node node, int defaultExpandLeval, int currentLevel) { nodes.add(node); if (defaultExpandLeval >= currentLevel) { node.setExpand(true); } if (node.isLeaf()) return; for (int i = 0; i < node.getChildrenNodes().size(); i++) { addNode(nodes, node.getChildrenNodes().get(i), defaultExpandLeval, currentLevel + 1); } } /** * 獲取所有的根節點 * * @param nodes * @return */ public static List<Node> getRootNodes(List<Node> nodes) { List<Node> rootNodes = new ArrayList<Node>(); for (Node node : nodes) { if (node.isRoot()) { rootNodes.add(node); } } return rootNodes; } /** * 將泛型datas轉換為node * * @param datas * @return * @throws IllegalArgumentException * @throws IllegalAccessException */ public static <T> List<Node> convertData2Nodes(List<T> datas, boolean isHide) throws IllegalAccessException, IllegalArgumentException { List<Node> nodes = new ArrayList<Node>(); Node node = null; for (T t : datas) { int id = -1; int pId = -1; String name = null; Class<? extends Object> clazz = t.getClass(); Field[] declaredFields = clazz.getDeclaredFields(); /** * 與MyNodeBean實體一一對應 */ for (Field f : declaredFields) { if ("id".equals(f.getName())) { f.setAccessible(true); id = f.getInt(t); } if ("pId".equals(f.getName())) { f.setAccessible(true); pId = f.getInt(t); } if ("name".equals(f.getName())) { f.setAccessible(true); name = (String) f.get(t); } if ("desc".equals(f.getName())) { continue; } if ("length".equals(f.getName())) { continue; } if (id == -1 && pId == -1 && name == null) { break; } } node = new Node(id, pId, name); node.setHideChecked(isHide); nodes.add(node); } /** * 比較nodes中的所有節點,分別添加children和parent */ 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 (n.getId() == m.getpId()) { n.getChildrenNodes().add(m); m.setParent(n); } else if (n.getpId() == m.getId()) { n.setParent(m); m.getChildrenNodes().add(n); } } } for (Node n : nodes) { setNodeIcon(n); } return nodes; } /** * 設置打開,關閉icon * * @param node */ public static void setNodeIcon(Node node) { if (node.getChildrenNodes().size() > 0 && node.isExpand()) { node.setIcon(R.drawable.tree_expand); } else if (node.getChildrenNodes().size() > 0 && !node.isExpand()) { node.setIcon(R.drawable.tree_econpand); } else node.setIcon(-1); } public static void setNodeChecked(Node node, boolean isChecked) { // 自己設置是否選擇 node.setChecked(isChecked); /** * 非葉子節點,子節點處理 */ setChildrenNodeChecked(node, isChecked); /** 父節點處理 */ setParentNodeChecked(node); } /** * 非葉子節點,子節點處理 */ private static void setChildrenNodeChecked(Node node, boolean isChecked) { node.setChecked(isChecked); if (!node.isLeaf()) { for (Node n : node.getChildrenNodes()) { // 所有子節點設置是否選擇 setChildrenNodeChecked(n, isChecked); } } } /** * 設置父節點選擇 * * @param node */ private static void setParentNodeChecked(Node node) { /** 非根節點 */ if (!node.isRoot()) { Node rootNode = node.getParent(); boolean isAllChecked = true; for (Node n : rootNode.getChildrenNodes()) { if (!n.isChecked()) { isAllChecked = false; break; } } if (isAllChecked) { rootNode.setChecked(true); } else { rootNode.setChecked(false); } setParentNodeChecked(rootNode); } } }
核心的代碼就是這些,希望對大家有幫助。
DEMO源碼:http://xiazai.jb51.net/201611/yuanma/AndroidTreeView(jb51.net).rar
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持本站。
貝塞爾曲線,很多人可能不太了解,什麼叫做貝塞爾曲線呢?這裡先做一下簡單介紹:貝塞爾曲線也可以叫做
1、概述本文主要講解的是如何自定義一個時間鐘表,通過簡單的練習可以簡單學習Android當中自定義view的一些常用繪圖技巧,優化android繪圖操作。言歸正傳,首先看
Action bar允許你為與當前應用上下文相關的最重要的action items添加action按鈕。那些直接顯示在action bar上的icon或者文字都被稱作ac
小米edge什麼時候上市?相信很多米粉對於小米edge手機很是期待和關注,紛紛上網咨詢,下文介紹小米edge上市時間,一起和小編來了解下吧! 小米edge