以编程方式更改ConstraintLayout中的宽度和高度不起作用

时间:2018-07-12 06:10:06

标签: android android-layout android-constraintlayout

我想以编程方式将以下UI更改为全屏。

<android.support.constraint.ConstraintLayout
    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:id="@+id/layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    >

    <TextView
        android:id="@+id/one"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ONE"
        android:background="@android:color/darker_gray"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintRight_toLeftOf="@+id/two"

        />

    <TextView
        android:id="@+id/two"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TWO"
        android:background="@android:color/holo_blue_dark"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toRightOf="@+id/one"
        />

</android.support.constraint.ConstraintLayout>

在我的Kotlin文件中:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val param = ConstraintLayout.LayoutParams(0, 0)

        one.layoutParams = param
        two.layoutParams = param
    }
}

在我将宽度和高度设置为0而不是全屏刮擦之后,两个TextView都消失了。

所需的UI enter image description here

1 个答案:

答案 0 :(得分:2)

您做错了。您必须应用新的ConstraintSet,例如:

val constraintSet1 = ConstraintSet()
constraintSet1.clone(yourConstraintLayout)

val constraintSet2 = ConstraintSet()
constraintSet2.clone(yourConstraintLayout)
constraintSet2.constrainWidth(R.id.one, 0)
constraintSet2.constrainWidth(R.id.two, 0)
constraintSet2.constrainHeight(R.id.one, 0)
constraintSet2.constrainHeight(R.id.two, 0)

// to switch to full screen
constraintSet2.applyTo(yourConstraintLayout)

// to get back to your original screen
constraintSet1.applyTo(yourConstraintLayout)