繁体   English   中英

以编程方式设置视图的 layout_weight

[英]Programmatically setting the layout_weight of a View

我希望能够以编程方式设置此视图的 layout_weight。 我怎样才能做到这一点?

final View v = (View) view.findViewById(R.id.vote_bar);

我试过这个,但它总是将它设置为最大值,即 100

v.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 5f));

这是布局

<LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignTop="@+id/text1"
            android:layout_alignBottom="@+id/text1"
            android:weightSum="100"
            android:orientation="horizontal">

            <View
                android:id="@+id/vote_bar"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:background="#68b4ff"
                android:padding="10dp"/>

        </LinearLayout>

XML

<LinearLayout
            android:id="@+id/lldashboard"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignTop="@+id/text1"
            android:layout_alignBottom="@+id/text1"
            android:weightSum="100"
            android:orientation="horizontal">

            <CardView
                android:id="@+id/cvModule"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="#68b4ff"
                android:padding="10dp"/>

               //other layouts

        </LinearLayout> 

Kotlin 文件获取视图高度

val viewTreeObserver = lldashboard.viewTreeObserver
        viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                lldashboard.viewTreeObserver.removeOnGlobalLayoutListener(this)
                val height = lldashboard.measuredHeight  
            }
        })

设置高度以查看

mBinding.cvModule.layoutParams.height = ((height / 5).toInt())

您应该能够执行以下操作:

<LinearLayout
            android:id="@+id/linearLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignTop="@+id/text1"
            android:layout_alignBottom="@+id/text1"
            android:weightSum="100"
            android:orientation="horizontal">

            <View
                android:id="@+id/vote_bar"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:background="#68b4ff"
                android:padding="10dp"/>

        </LinearLayout>
LinearLayout ll = findViewById(R.id.linearLayout)
ll.setWeightSum(2f);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM