我有一个节点的树结构(想想文件夹和文件),我想在RecyclerView中显示。我让它可以看到所有可见的节点,但我还是试图实现折叠和扩展节点。
这是我到目前为止所拥有的。基本节点如下所示:
public class Node {
List<Node> children = new ArrayList<>();
Node parent = null;
String name = "";
// If 'false', do not show child views
boolean visible = true;
}
适配器获取List
个节点并按如下方式填充它们:
private List<Node> nodes = new ArrayList<>();
// Takes a list of root-level nodes and "flattens"
// them to the nodes fields
public void addNodes(List<Node> nodes) {
for(Node n : nodes) {
this.nodes.add(n);
addNodes(n.children);
}
}
// Binds a node to a viewholder
@Override
void onBindViewHolder(ViewHolder holder, int position) {
holder.textView.setText(nodes.get(position).name);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Collapse / expand the children of the node
toggleNode(nodes.get(position));
}
});
}
// This "works", but tends to get screwed up after a while,
// especially when hiding and showing nodes at different depths
// in the same hierarchy
private void toggleNode(Node node) {
node.visible = !node.visible;
for(Node child : node.children) {
if(node.visible) notifyItemInserted(nodes.indexOf(child));
else notifyItemRemoved(nodes.indexOf(child));
}
}
有关如何使其按预期工作的任何想法?