自定义 ViewGroup 示例?

发布于 2024-11-01 06:44:38 字数 125 浏览 3 评论 0原文

我在这里搜索过,在谷歌上,在android文档上...

但是我找不到带有自定义视图组示例的代码片段,我最多找到一些模糊的解释...

有人可以提供一个吗?如何创建一个视图组,以便将其子项放置在您想要的位置?

I searched here on SO, on Google, on the android docs...

But I cannot find a single snippet of code with a example of custom viewgroup, I find at most some vague explanations...

Can someone provide one? How you make a viewgroup where you can put its children where you want?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

喜爱皱眉﹌ 2024-11-08 06:44:38

我认为最简单的例子是 AbsoluteLayout.java

https://github.com/android/platform_frameworks_base/blob/master/core/java/android/widget/AbsoluteLayout.java

您需要重写 onMeasure 来测量子级,并重写 onLayout 来定位它们。

如果您愿意,我也可以分享更加复杂的 ViewGroup 代码。

I think the simplest example to look at is the source for AbsoluteLayout.java

https://github.com/android/platform_frameworks_base/blob/master/core/java/android/widget/AbsoluteLayout.java

You need to override onMeasure to measure the children and onLayout to position them.

I have strikingly more complicated ViewGroup code I can share as well if you want.

眼眸印温柔 2024-11-08 06:44:38

这并不简单,您需要做的就是在计算出视图的精确尺寸后调用 super.onMeasure

class ProportionalConstraintLayout @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {
    
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {

        val exactWidth = 100 //do something to calculate the view widht
        val exactHeight = 100 //do something to calculate the view height

        setMeasuredDimension(exactWidth, exactHeight)
        super.onMeasure(
            MeasureSpec.makeMeasureSpec(exactWidth, MeasureSpec.EXACTLY),
            MeasureSpec.makeMeasureSpec(exactHeight, MeasureSpec.EXACTLY)
        )

    }

}

It't quite simple, all you need to do is to call super.onMeasure after calculate the exact dimentions of yout view.

class ProportionalConstraintLayout @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {
    
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {

        val exactWidth = 100 //do something to calculate the view widht
        val exactHeight = 100 //do something to calculate the view height

        setMeasuredDimension(exactWidth, exactHeight)
        super.onMeasure(
            MeasureSpec.makeMeasureSpec(exactWidth, MeasureSpec.EXACTLY),
            MeasureSpec.makeMeasureSpec(exactHeight, MeasureSpec.EXACTLY)
        )

    }

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文