gpt4 book ai didi

android - 根据 parent 调整 View 大小

转载 作者:行者123 更新时间:2023-11-30 01:04:03 26 4
gpt4 key购买 nike

我创建了一个正在绘制圆圈的自定义 View 。它从 xml 中获取圆圈数。

例如它在整个屏幕上生成 10 个圆圈。

<com.dd.view.MyShape
android:layout_width="match_parent"
android:layout_height="60dp"
app:shape_count="10"/>

enter image description here

<LinearLayout
android:layout_width="80dp"
android:layout_height="wrap_content"
android:orientation="vertical">

<com.dd.view.MyShape
android:layout_width="100dp"
android:layout_height="60dp"
app:shape_count="3"/>
</LinearLayout>

但是当我将这个 View 放入较小的布局时,圆圈会根据 View 的宽度生成。我想根据父 View 生成。

我试图覆盖 onMeasure 方法,但无法正确覆盖。现在看起来像:

enter image description here

这是我的 onDraw 方法:

 @Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int totalWidth=getMeasuredWidth();
int major = totalWidth / circleCount;
int radius = major/2;
float startPoint = totalWidth / (circleCount * 2);
for (int i = 0; i < circleCount; i++) {
if (i % 2 == 0) paint.setColor(Color.GREEN);
else paint.setColor(Color.BLUE);
canvas.drawCircle(startPoint + major * i, radius,radius, paint);
}
}

感谢您的回答。

最佳答案

在 xml 中,对于自定义小部件,使 layout_width="match_parent"而不是在自定义 View java 类中实现,它将采用父级的宽度。

<LinearLayout
android:layout_width="80dp"
android:layout_height="wrap_content"
android:orientation="vertical">

<com.dd.view.MyShape
android:layout_width="match_parent"
android:layout_height="60dp"
app:shape_count="3"/>

</LinearLayout>

关于android - 根据 parent 调整 View 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39057496/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com