private MyTreeListViewAdapter adapter;
private List mDatas = new ArrayList();
//标记是显示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(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 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;
impo