初始化后如何获取片段的宽度/高度

问题描述

我正在开发使用 SDK 的应用程序,它将为我提供一个简单的小部件,我需要将其包含在我的应用程序中。该 Widget 是具有动态高度的片段(取决于 API 响应,它可以显示不同的信息)

我遇到的问题是我需要设置布局高度,但不知道小部件(片段)是否适合内部。

我尝试了以下几个选项:

设置 LinearLayout,里面有 minHeight="100dp"CardView,我用来在其中显示小部件:

                <LinearLayout
                    android:id="@+id/linearLayout"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="16dp"
                    android:layout_marginTop="16dp"
                    android:layout_marginEnd="16dp"
                    android:minHeight="100dp"
                    android:orientation="vertical"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="parent">

                    <androidx.cardview.widget.CardView
                        android:id="@+id/widget_container"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent" />

                </LinearLayout>

但是这种方法不起作用,因为如果小部件大于/小于 100dp,布局将不会自行调整大小。

我的想法是尝试获取片段宽度/高度并将该属性设置为我的布局,然后我将使用 childFragmentManager 将 cardview 替换为我的小部件片段。

import com.custom.sdk.ui.MySuperWidget
...
    override fun onViewCreated(view: View,savedInstanceState: Bundle?) {
        super.onViewCreated(view,savedInstanceState)

        //Try to get Width and Height
        val myWidget = MySuperWidget()

        //Update linear layout width and height
        val myWidgetContainerLayout = widget_container
        val parameters: LinearLayout.LayoutParams = myWidgetContainerLayout.layoutParams
        newParameters.width = 100
        newParameters.height = 325
        myWidgetContainerLayout.layoutParams = newParameters

        //Replace fragment
        childFragmentManager.beginTransaction().replace(R.id.widget_container,myWidget).commit()
    }
}

我使用此响应 https://stackoverflow.com/a/57259721/5270396 作为想法在替换片段之前以编程方式设置 LinearLayout 属性,但我无法获取片段高度/宽度

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)