Android TreeView可以通過自定義Adapter來實現。以下是一個簡單的示例代碼:
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) {
// 實現group視圖的繪制
return null;
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
// 實現child視圖的繪制
return null;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
TreeView treeView = findViewById(R.id.treeView);
List<TreeItem> rootItems = new ArrayList<>();
// 構建樹結構
TreeAdapter treeAdapter = new TreeAdapter(rootItems);
treeView.setAdapter(treeAdapter);
通過以上步驟,就可以實現一個簡單的Android TreeView。在TreeAdapter中,可以根據需要自定義group和child視圖的繪制邏輯,以實現不同的展示效果。