【问题标题】:how to change a view height programmatically based on a layout height如何根据布局高度以编程方式更改视图高度
【发布时间】:2022-01-14 16:33:47
【问题描述】:

我正在开发一个应用程序,我需要创建一种看起来像仪表的磁贴。所以基本上,我创建了一个简单的 xml 文件。带有我需要的布局和所有视图,如下所示:

<androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/tile_layout"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_columnWeight="1"
        android:background="@color/transparent">

        <View
            android:id="@+id/gauge"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="invisible"/>
...

在片段中,我正在做的事情:

        val layout: ConstraintLayout = view.findViewById(R.id.tile_layout)
        val gauge = view.findViewById<View>(R.id.gauge)
        val ratio = 75


        view.layoutParams = getParams()
        val newParams: ViewGroup.LayoutParams = gauge.layoutParams
        newParams.height = (layout.height * ratio / 100)
        gauge.setLayoutParams(newParams)

它不起作用,高度仍然相同。我希望仪表视图高度约为布局高度的 75%。

知道怎么做吗?

【问题讨论】:

    标签: android kotlin layout android-constraintlayout


    【解决方案1】:

    我认为您需要在完全创建布局时通过添加OnGlobalLayoutListener 来获取高度;然后使用layout.measuredHeight 而不是layout.height

    val layout: ConstraintLayout = view.findViewById(R.id.tile_layout)
    val gauge = view.findViewById<View>(R.id.gauge)
    
    layout.viewTreeObserver.addOnGlobalLayoutListener(object :
        ViewTreeObserver.OnGlobalLayoutListener {
        override fun onGlobalLayout() {
    
            val ratio = 75
            view.layoutParams = getParams()
            val newParams: ViewGroup.LayoutParams = gauge.layoutParams
            newParams.height = (layout.measuredHeight * ratio / 100)
            gauge.layoutParams = newParams
            layout.viewTreeObserver.removeOnGlobalLayoutListener(this)
        }
    
    })
    

    【讨论】:

      【解决方案2】:

      Zain 所说的可能是正确的,但您没有显示足够的代码来判断这是否正确。我会说您的仪表视图没有设置约束,并且约束是 ConstraintLayout 的每个直接子级都应该具有的,并且match_parent 是无效的。请参阅ConstraintLayout 的文档。

      重要提示:不建议将 MATCH_PARENT 用于 ConstraintLayout 中包含的小部件。类似的行为可以通过使用 MATCH_CONSTRAINT 来定义,并将相应的左/右或上/下约束设置为“父”。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-08
        • 2018-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多