在自定义视图中绘制自定义视图

我正在处理自定义视图TreeView ,它将显示给定根节点的树。 我正在使用Kotlin语言。

以下是目前的部分内容:

 override fun onDraw(canvas: Canvas?) { super.onDraw(canvas) drawNodeAndChildren(canvas, rootNode) } /** * Draws a representation of a node and its children onto the canvas. * ... */ private fun drawNodeAndChildren(canvas: Canvas, node: TreeNode, ...): Int { ... // Calculate coordinates of rect val top = ... val bottom = ... val left = ... val right = ... // Draw node representation val rect = RectF(left, top, right, bottom) canvas.drawRect(rect, nodePaint) // Draw line to connect to parent ... // Repeat for children ... } 

这工作顺利,我能够产生一个矩形代表父母和孩子之间的节点和线条的视觉树。

但是,我希望能够显示人物的图像和文字。 我已经写了一个名为PersonView的复合视图,它能够给定一个Person对象。 理想情况下,用户将来可以在TreeView点击这些PersonView来触发一个动作。

所以基本上,而不是矩形, PersonView将被绘制。

我已经尝试以编程方式创建视图,并像这样设置其布局参数:

  ... val personView = PersonView(context).apply { person = node.data } val layoutParams = ViewGroup.LayoutParams( (right - left).toInt(), // width (bottom - top).toInt() // height ) personView.layoutParams = layoutParams personView.x = left personView.y = top personView.draw(canvas) ... 

我也试过:

  ... val personView = PersonView(context).apply { person = node.data } personView.layout(left.toInt(), top.toInt(), right.toInt(), bottom.toInt()) personView.draw(canvas) ... 

在这两种情况下,都没有画出矩形,而是仿佛上面的两个代码样本没有效果。

注意矩形所在之处(即节点之间的连接)之间的界线,这部分代码没有被改变。

所以我的问题是如何在另一个自定义视图中绘制一个自定义视图,以便我可以得到我所描述的效果?