Android TreeView可以通過自定義Adapter來實(shí)現(xiàn)。以下是一個(gè)簡單的示例代碼:
public class TreeItem {
private String name;
private List<TreeItem> children;
public TreeItem(String name) {
this.name = name;
this.children = new ArrayList<>();
}
public String getName() {
return name;
}
public List<TreeItem> getChildren() {
return children;
}
public void addChild(TreeItem child) {
children.add(child);
}
}
public class TreeAdapter extends BaseExpandableListAdapter {
private List<TreeItem> rootItems;
public TreeAdapter(List<TreeItem> rootItems) {
this.rootItems = rootItems;
}
@Override
public int getGroupCount() {
return rootItems.size();
}
@Override
public int getChildrenCount(int groupPosition) {
return rootItems.get(groupPosition).getChildren().size();
}
@Override
public Object getGroup(int groupPosition) {
return rootItems.get(groupPosition);
}
@Override
public Object getChild(int groupPosition, int childPosition) {
return rootItems.get(groupPosition).getChildren().get(childPosition);
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
// 實(shí)現(xiàn)group視圖的繪制
return null;
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
// 實(shí)現(xiàn)child視圖的繪制
return null;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
TreeView treeView = findViewById(R.id.treeView);
List<TreeItem> rootItems = new ArrayList<>();
// 構(gòu)建樹結(jié)構(gòu)
TreeAdapter treeAdapter = new TreeAdapter(rootItems);
treeView.setAdapter(treeAdapter);
通過以上步驟,就可以實(shí)現(xiàn)一個(gè)簡單的Android TreeView。在TreeAdapter中,可以根據(jù)需要自定義group和child視圖的繪制邏輯,以實(shí)現(xiàn)不同的展示效果。