所謂TreeView就是在Windows中常見的多級列表樹,在Android中系統隻默認提供瞭ListView和ExpandableListView兩種列表,最多隻支持到二級列表的實現,所以如果想要實現三級和更多層次的列表,就需要我們自己來做一些處理瞭。
其實這個效果很久以前就有人想辦法實現瞭,但是實現的效果有一些問題,我的實現思路主要也是來自於網絡,但是在其基礎上修正瞭邏輯上的一些錯誤,做瞭一些優化。
然後大體說一下思路:
其實這裡實現的多級列表隻是一個視覺效果,我們看到的分級效果是由於每行的縮進不同造成的。比如在上面的效果中,山東省和廣東省是級別最高的層次,山東省下的青島市作為山東省的子項,我們增加他的左縮進,這樣看起來就有瞭層次感瞭。其他的層次也是同理。
也就是說,我們隻用瞭一個ListView,工作的重點就在於不斷變化ListView顯示的數據,根據用戶的操作,將數據修改為用戶想要看到的數據內容,並根據每個數據項的不同,在顯示效果上做不同的縮進處理,最終呈現出一個TreeView的效果。
具體的實現思路參考下面的項目結構和具體代碼:
Element.java:
[java]
package com.example.androidtreeviewdemo.treeview;
/**
* Element類
* @author carrey
*
*/
public class Element {
/** 文字內容 */
private String contentText;
/** 在tree中的層級 */
private int level;
/** 元素的id */
private int id;
/** 父元素的id */
private int parendId;
/** 是否有子元素 */
private boolean hasChildren;
/** item是否展開 */
private boolean isExpanded;
/** 表示該節點沒有父元素,也就是level為0的節點 */
public static final int NO_PARENT = -1;
/** 表示該元素位於最頂層的層級 */
public static final int TOP_LEVEL = 0;
public Element(String contentText, int level, int id, int parendId,
boolean hasChildren, boolean isExpanded) {
super();
this.contentText = contentText;
this.level = level;
this.id = id;
this.parendId = parendId;
this.hasChildren = hasChildren;
this.isExpanded = isExpanded;
}
public boolean isExpanded() {
return isExpanded;
}
public void setExpanded(boolean isExpanded) {
this.isExpanded = isExpanded;
}
public String getContentText() {
return contentText;
}
public void setContentText(String contentText) {
this.contentText = contentText;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getParendId() {
return parendId;
}
public void setParendId(int parendId) {
this.parendId = parendId;
}
public boolean isHasChildren() {
return hasChildren;
}
public void setHasChildren(boolean hasChildren) {
this.hasChildren = hasChildren;
}
}
package com.example.androidtreeviewdemo.treeview;
/**
* Element類
* @author carrey
*
*/
public class Element {
/** 文字內容 */
private String contentText;
/** 在tree中的層級 */
private int level;
/** 元素的id */
private int id;
/** 父元素的id */
private int parendId;
/** 是否有子元素 */
private boolean hasChildren;
/** item是否展開 */
private boolean isExpanded;
/** 表示該節點沒有父元素,也就是level為0的節點 */
public static final int NO_PARENT = -1;
/** 表示該元素位於最頂層的層級 */
public static final int TOP_LEVEL = 0;
public Element(String contentText, int level, int id, int parendId,
boolean hasChildren, boolean isExpanded) {
super();
this.contentText = contentText;
this.level = level;
this.id = id;
this.parendId = parendId;
this.hasChildren = hasChildren;
this.isExpanded = isExpanded;
}
public boolean isExpanded() {
return isExpanded;
}
public void setExpanded(boolean isExpanded) {
this.isExpanded = isExpanded;
}
public String getContentText() {
return contentText;
}
public void setContentText(String contentText) {
this.contentText = contentText;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getParendId() {
return parendId;
}
public void setParendId(int parendId) {
this.parendId = parendId;
}
public boolean isHasChildren() {
return hasChildren;
}
public void setHasChildren(boolean hasChildren) {
this.hasChildren = hasChildren;
}
}
TreeViewAdapter.java:
[java]
package com.example.androidtreeviewdemo.treeview;
import java.util.ArrayList;
import com.example.androidtreeviewdemo.R;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/**
* TreeViewAdapter
* @author carrey
*
*/
public class TreeViewAdapter extends BaseAdapter {
/** 元素數據源 */
private ArrayList<Element> elementsData;
/** 樹中元素 */
private ArrayList<Element> elements;
/** LayoutInflater */
private LayoutInflater inflater;
/** item的行首縮進基數 */
private int indentionBase;
public TreeViewAdapter(ArrayList<Element> elements, ArrayList<Element> elementsData, LayoutInflater inflater) {
this.elements = elements;
this.elementsData = elementsData;
this.inflater = inflater;
indentionBase = 50;
}
public ArrayList<Element> getElements() {
return elements;
}
public ArrayList<Element> getElementsData() {
return elementsData;
}
@Override
public int getCount() {
return elements.size();
}
@Override
public Object getItem(int position) {
return elements.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.treeview_item, null);
holder.disclosureImg = (ImageView) convertView.findViewById(R.id.disclosureImg);
holder.contentText = (TextView) convertView.findViewById(R.id.contentText);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Element element = elements.get(position);
int level = element.getLevel();
holder.disclosureImg.setPadding(
indentionBase * (level + 1),
holder.disclosureImg.getPaddingTop(),
holder.disclosureImg.getPaddingRight(),
holder.disclosureImg.getPaddingBottom());
holder.contentText.setText(element.getContentText());
if (element.isHasChildren() && !element.isExpanded()) {
holder.disclosureImg.setImageResource(R.drawable.close);
//這裡要主動設置一下icon可見,因為convertView有可能是重用瞭"設置瞭不可見"的view,下同。
holder.disclosureImg.setVisibility(View.VISIBLE);
} else if (element.isHasChildren() && element.isExpanded()) {
holder.disclosureImg.setImageResource(R.drawable.open);
holder.disclosureImg.setVisibility(View.VISIBLE);
} else if (!element.isHasChildren()) {
holder.disclosureImg.setImageResource(R.drawable.close);
holder.disclosureImg.setVisibility(View.INVISIBLE);
}
return convertView;
}
/**
* 優化Holder
* @author carrey
*
*/
static class ViewHolder{
ImageView disclosureImg;
TextView contentText;
}
}
package com.example.androidtreeviewdemo.treeview;
import java.util.ArrayList;
import com.example.androidtreeviewdemo.R;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/**
* TreeViewAdapter
* @author carrey
*
*/
public class TreeViewAdapter extends BaseAdapter {
/** 元素數據源 */
private ArrayList<Element> elementsData;
/** 樹中元素 */
private ArrayList<Element> elements;
/** LayoutInflater */
private LayoutInflater inflater;
/** item的行首縮進基數 */
private int indentionBase;
public TreeViewAdapter(ArrayList<Element> elements, ArrayList<Element> elementsData, LayoutInflater inflater) {
this.elements = elements;
this.elementsData = elementsData;
this.inflater = inflater;
indentionBase = 50;
}
public ArrayList<Element> getElements() {
return elements;
}
public ArrayList<Element> getElementsData() {
return elementsData;
}
@Override
public int getCount() {
return elements.size();
}
@Override
public Object getItem(int position) {
return elements.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.treeview_item, null);
holder.disclosureImg = (ImageView) convertView.findViewById(R.id.disclosureImg);
holder.contentText = (TextView) convertView.findViewById(R.id.contentText);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Element element = elements.get(position);
int level = element.getLevel();
holder.disclosureImg.setPadding(
indentionBase * (level + 1),
holder.disclosureImg.getPaddingTop(),
holder.disclosureImg.getPaddingRight(),
holder.disclosureImg.getPaddingBottom());
holder.contentText.setText(element.getContentText());
if (element.isHasChildren() && !element.isExpanded()) {
holder.disclosureImg.setImageResource(R.drawable.close);
//這裡要主動設置一下icon可見,因為convertView有可能是重用瞭"設置瞭不可見"的view,下同。
holder.disclosureImg.setVisibility(View.VISIBLE);
} else if (element.isHasChildren() && element.isExpanded()) {
holder.disclosureImg.setImageResource(R.drawable.open);
holder.disclosureImg.setVisibility(View.VISIBLE);
} else if (!element.isHasChildren()) {
holder.disclosureImg.setImageResource(R.drawable.close);
holder.disclosureImg.setVisibility(View.INVISIBLE);
}
return convertView;
}
/**
* 優化Holder
* @author carrey
*
*/
static class ViewHolder{
ImageView disclosureImg;
TextView contentText;
}
}
TreeViewItemClickListener.java:
[java]
package com.example.androidtreeviewdemo.treeview;
import java.util.ArrayList;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
/**
* TreeView item點擊事件
* @author carrey
*
*/
public class TreeViewItemClickListener implements OnItemClickListener {
/** adapter */
private TreeViewAdapter treeViewAdapter;
public TreeViewItemClickListener(TreeViewAdapter treeViewAdapter) {
this.treeViewAdapter = treeViewAdapter;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
//點擊的item代表的元素
Element element = (Element) treeViewAdapter.getItem(position);
//樹中的元素
ArrayList<Element> elements = treeViewAdapter.getElements();
//元素的數據源
ArrayList<Element> elementsData = treeViewAdapter.getElementsData();
//點擊沒有子項的item直接返回
if (!element.isHasChildren()) {
return;
}
if (element.isExpanded()) {
element.setExpanded(false);
//刪除節點內部對應子節點數據,包括子節點的子節點…
ArrayList<Element> elementsToDel = new ArrayList<Element>();
for (int i = position + 1; i < elements.size(); i++) {
if (element.getLevel() >= elements.get(i).getLevel())
break;
elementsToDel.add(elements.get(i));
}
elements.removeAll(elementsToDel);
treeViewAdapter.notifyDataSetChanged();
} else {
element.setExpanded(true);
//從數據源中提取子節點數據添加進樹,註意這裡隻是添加瞭下一級子節點,為瞭簡化邏輯
int i = 1;//註意這裡的計數器放在for外面才能保證計數有效
for (Element e : elementsData) {
if (e.getParendId() == element.getId()) {
e.setExpanded(false);
elements.add(position + i, e);
i ++;
}
}
treeViewAdapter.notifyDataSetChanged();
}
}
}
package com.example.androidtreeviewdemo.treeview;
import java.util.ArrayList;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
/**
* TreeView item點擊事件
* @author carrey
*
*/
public class TreeViewItemClickListener implements OnItemClickListener {
/** adapter */
private TreeViewAdapter treeViewAdapter;
public TreeViewItemClickListener(TreeViewAdapter treeViewAdapter) {
this.treeViewAdapter = treeViewAdapter;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
//點擊的item代表的元素
Element element = (Element) treeViewAdapter.getItem(position);
//樹中的元素
ArrayList<Element> elements = treeViewAdapter.getElements();
//元素的數據源
ArrayList<Element> elementsData = treeViewAdapter.getElementsData();
//點擊沒有子項的item直接返回
if (!element.isHasChildren()) {
return;
}
if (element.isExpanded()) {
element.setExpanded(false);
//刪除節點內部對應子節點數據,包括子節點的子節點…
ArrayList<Element> elementsToDel = new ArrayList<Element>();
for (int i = position + 1; i < elements.size(); i++) {
if (element.getLevel() >= elements.get(i).getLevel())
break;
elementsToDel.add(elements.get(i));
}
elements.removeAll(elementsToDel);
treeViewAdapter.notifyDataSetChanged();
} else {
element.setExpanded(true);
//從數據源中提取子節點數據添加進樹,註意這裡隻是添加瞭下一級子節點,為瞭簡化邏輯
int i = 1;//註意這裡的計數器放在for外面才能保證計數有效
for (Element e : elementsData) {
if (e.getParendId() == element.getId()) {
e.setExpanded(false);
elements.add(position + i, e);
i ++;
}
}
treeViewAdapter.notifyDataSetChanged();
}
}
}
MainActivity.java:
[java]
package com.example.androidtreeviewdemo;
import java.util.ArrayList;
import com.example.androidtreeviewdemo.treeview.Element;
import com.example.androidtreeviewdemo.treeview.TreeViewAdapter;
import com.example.androidtreeviewdemo.treeview.TreeViewItemClickListener;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.Menu;
import android.widget.ListView;
public class MainActivity extends Activity {
/** 樹中的元素集合 */
private ArrayList<Element> elements;
/** 數據源元素集合 */
private ArrayList<Element> elementsData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
init();
ListView treeview = (ListView) findViewById(R.id.treeview);
TreeViewAdapter treeViewAdapter = new TreeViewAdapter(
elements, elementsData, inflater);
TreeViewItemClickListener treeViewItemClickListener = new TreeViewItemClickListener(treeViewAdapter);
treeview.setAdapter(treeViewAdapter);
treeview.setOnItemClickListener(treeViewItemClickListener);
}
private void init() {
elements = new ArrayList<Element>();
elementsData = new ArrayList<Element>();
//添加節點 — 節點名稱,節點level,節點id,父節點id,是否有子節點,是否展開
//添加最外層節點
Element e1 = new Element("山東省", Element.TOP_LEVEL, 0, Element.NO_PARENT, true, false);
//添加第一層節點
Element e2 = new Element("青島市", Element.TOP_LEVEL + 1, 1, e1.getId(), true, false);
//添加第二層節點
Element e3 = new Element("市南區", Element.TOP_LEVEL + 2, 2, e2.getId(), true, false);
//添加第三層節點
Element e4 = new Element("香港中路", Element.TOP_LEVEL + 3, 3, e3.getId(), false, false);
//添加第一層節點
Element e5 = new Element("煙臺市", Element.TOP_LEVEL + 1, 4, e1.getId(), true, false);
//添加第二層節點
Element e6 = new Element("芝罘區", Element.TOP_LEVEL + 2, 5, e5.getId(), true, false);
//添加第三層節點
Element e7 = new Element("鳳凰臺街道", Element.TOP_LEVEL + 3, 6, e6.getId(), false, false);
//添加第一層節點
Element e8 = new Element("威海市", Element.TOP_LEVEL + 1, 7, e1.getId(), false, false);
//添加最外層節點
Element e9 = new Element("廣東省", Element.TOP_LEVEL, 8, Element.NO_PARENT, true, false);
//添加第一層節點
Element e10 = new Element("深圳市", Element.TOP_LEVEL + 1, 9, e9.getId(), true, false);
//添加第二層節點
Element e11 = new Element("南山區", Element.TOP_LEVEL + 2, 10, e10.getId(), true, false);
//添加第三層節點
Element e12 = new Element("深南大道", Element.TOP_LEVEL + 3, 11, e11.getId(), true, false);
//添加第四層節點
Element e13 = new Element("10000號", Element.TOP_LEVEL + 4, 12, e12.getId(), false, false);
//添加初始樹元素
elements.add(e1);
elements.add(e9);
//創建數據源
elementsData.add(e1);
elementsData.add(e2);
elementsData.add(e3);
elementsData.add(e4);
elementsData.add(e5);
elementsData.add(e6);
elementsData.add(e7);
elementsData.add(e8);
elementsData.add(e9);
elementsData.add(e10);
elementsData.add(e11);
elementsData.add(e12);
elementsData.add(e13);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
package com.example.androidtreeviewdemo;
import java.util.ArrayList;
import com.example.androidtreeviewdemo.treeview.Element;
import com.example.androidtreeviewdemo.treeview.TreeViewAdapter;
import com.example.androidtreeviewdemo.treeview.TreeViewItemClickListener;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.Menu;
import android.widget.ListView;
public class MainActivity extends Activity {
/** 樹中的元素集合 */
private ArrayList<Element> elements;
/** 數據源元素集合 */
private ArrayList<Element> elementsData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
init();
ListView treeview = (ListView) findViewById(R.id.treeview);
TreeViewAdapter treeViewAdapter = new TreeViewAdapter(
elements, elementsData, inflater);
TreeViewItemClickListener treeViewItemClickListener = new TreeViewItemClickListener(treeViewAdapter);
treeview.setAdapter(treeViewAdapter);
treeview.setOnItemClickListener(treeViewItemClickListener);
}
private void init() {
elements = new ArrayList<Element>();
elementsData = new ArrayList<Element>();
//添加節點 — 節點名稱,節點level,節點id,父節點id,是否有子節點,是否展開
//添加最外層節點
Element e1 = new Element("山東省", Element.TOP_LEVEL, 0, Element.NO_PARENT, true, false);
//添加第一層節點
Element e2 = new Element("青島市", Element.TOP_LEVEL + 1, 1, e1.getId(), true, false);
//添加第二層節點
Element e3 = new Element("市南區", Element.TOP_LEVEL + 2, 2, e2.getId(), true, false);
//添加第三層節點
Element e4 = new Element("香港中路", Element.TOP_LEVEL + 3, 3, e3.getId(), false, false);
//添加第一層節點
Element e5 = new Element("煙臺市", Element.TOP_LEVEL + 1, 4, e1.getId(), true, false);
//添加第二層節點
Element e6 = new Element("芝罘區", Element.TOP_LEVEL + 2, 5, e5.getId(), true, false);
//添加第三層節點
Element e7 = new Element("鳳凰臺街道", Element.TOP_LEVEL + 3, 6, e6.getId(), false, false);
//添加第一層節點
Element e8 = new Element("威海市", Element.TOP_LEVEL + 1, 7, e1.getId(), false, false);
//添加最外層節點
Element e9 = new Element("廣東省", Element.TOP_LEVEL, 8, Element.NO_PARENT, true, false);
//添加第一層節點
Element e10 = new Element("深圳市", Element.TOP_LEVEL + 1, 9, e9.getId(), true, false);
//添加第二層節點
Element e11 = new Element("南山區", Element.TOP_LEVEL + 2, 10, e10.getId(), true, false);
//添加第三層節點
Element e12 = new Element("深南大道", Element.TOP_LEVEL + 3, 11, e11.getId(), true, false);
//添加第四層節點
Element e13 = new Element("10000號", Element.TOP_LEVEL + 4, 12, e12.getId(), false, false);
//添加初始樹元素
elements.add(e1);
elements.add(e9);
//創建數據源
elementsData.add(e1);
elementsData.add(e2);
elementsData.add(e3);
elementsData.add(e4);
elementsData.add(e5);
elementsData.add(e6);
elementsData.add(e7);
elementsData.add(e8);
elementsData.add(e9);
elementsData.add(e10);
elementsData.add(e11);
elementsData.add(e12);
elementsData.add(e13);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
treeview_item.xml:
[html]
?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/disclosureImg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"/>
<TextView
android:id="@+id/contentText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@id/disclosureImg"/>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/disclosureImg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"/>
<TextView
android:id="@+id/contentText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@id/disclosureImg"/>
</RelativeLayout>activity_main.xml:
[html]
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ListView
android:id="@+id/treeview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>