如何从 Kotlin 代码动态设置 Android 中 LinerLayout 的属性layout_weight 的值?
var orange : LinearLayout = findViewById(R.id.orangeLineFiveStars) as LinearLayout
Run Code Online (Sandbox Code Playgroud)
代码正确吗?[它在我的应用程序中不起作用]
var orangeParams : LinearLayout.LayoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
orangeParams.weight = 0.33f
orange.layoutParams = orangeParams
Run Code Online (Sandbox Code Playgroud)
这段代码也不起作用
var orange.layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT,0.33f)
Run Code Online (Sandbox Code Playgroud)
XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.sanke.ilafedoseev.raitmyworkstatistic.MainActivity">
<LinearLayout
android:layout_margin="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="@+id/orangeLineFiveStars"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="4dp"
android:background="#febe40"
android:orientation="horizontal"/>
<LinearLayout
android:id="@+id/whiteLineFiveStars"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"/>
</LinearLayout>
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)
小智 5
您需要记住布局参数是从子视图传递到父视图的。你可能想要改变layout_weightLinearLayout 的某些子级。
在你的情况下,你可能想做这样的事情
(orangeLineFiveStars.layoutParams as LinearLayout.LayoutParams).weight = newOrangeWeight
(whiteLineFiveStars.layoutParams as LinearLayout.LayoutParams).weight = newWhiteWeight
Run Code Online (Sandbox Code Playgroud)
可能还需要请求重新布局
parentLinearLayout.requestLayout()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6424 次 |
| 最近记录: |