如何在另一个 View 的 draw() 方法中从 XML 绘制布局?

How to draw layout from XML in another View's draw() method?

我在我的项目中使用 MPAndroidChart 并且我有一个饼图。我需要在饼图的中心绘制布局,但我必须在饼图中绘制它,而不是在顶部。

所以我修改了 PieChartRendererdrawCenterText(Canvas c) 以从 XML 文件绘制整个布局,而不仅仅是文本。我的 XML 文件是带有自动调整 TextView 大小的 ConstraintLayout。 XML 应该画在饼图的中心。

我在 MainActivity 中膨胀了 XML 并将其作为对 PieChart 的引用传递。

ViewGroup centerLayout = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.center_text_layout, mPieChart, false);
mPieChart.setCenterLayout(centerLayout);

现在,当 PieChart 必须绘制自己时,它还应该在其中心绘制 centerLayout。 drawCenterLayout(Canvas canvas) 方法计算应该在何处绘制 centerLayout。一切都很好,直到绘图本身。不知道为什么centerLayout根(ConstraintLayout)的children没有画出来。

这是一段应该绘制 centerLayout 的代码,来自 PieChart drawCenterLayout(Canvas canvas) 方法:

ViewGroup.LayoutParams params = centerLayout.getLayoutParams();
int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(params.width, View.MeasureSpec.EXACTLY);
int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(params.height, View.MeasureSpec.EXACTLY);

centerLayout.measure(widthMeasureSpec, heightMeasureSpec);
centerLayout.layout((int)boundingRect.left, (int)boundingRect.top, (int)boundingRect.right, (int)boundingRect.bottom);
centerLayout.draw(canvas);

canvas.restore();

这是我的 XML 以及中心应该是什么样子,文本是硬编码的(我已经对背景进行了着色):

这就是它最终的样子

很明显 children 设置不正确...我该怎么办? centerLayout.measure 方法也应该自动测量 children ,对吧?

问题出在测量方法上。我必须提供适当的参数。

int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(pieCenter.getWidth(), View.MeasureSpec.EXACTLY);
int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(pieCenter.getHeight(), View.MeasureSpec.EXACTLY);