【问题标题】:Add buttons programmatically to Flow of ConstraintLayout?以编程方式将按钮添加到 ConstraintLayout 流?
【发布时间】:2021-10-12 22:59:54
【问题描述】:

我在现有问题中看到了将按钮添加到 ConstraintLayout 的代码,但是如何使用 Flow 来做到这一点?也就是说,我不想定义按钮相对于 ConstraintView 本身的顶部/左侧,但我希望按钮位于前一个按钮旁边并在行尾换行。

我尝试了以下方法,但没有显示任何按钮。

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

    val flow = findViewById<Flow>(R.id.flow);
    val lay = flow.parent as ConstraintLayout;
    val cs = ConstraintSet();
    cs.clone(lay);

    for (i in 1 .. 10)
    {
        val btn = Button(this)
        btn.text = "Test ${i}";
        btn.id = 49393+i;
        flow.addView(btn)
        cs.constrainWidth(btn.id, 400);
        cs.constrainHeight(btn.id, 100);
        cs.applyTo(lay);
    }
}

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        xmlns:app="http://schemas.android.com/apk/res-auto">
    <ScrollView
            android:id="@+id/sv"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <TextView
                    android:id="@+id/textview1"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/large_text"
                    android:textAppearance="@style/TextAppearance.AppCompat.Large"
                    android:textIsSelectable="true" />
    </ScrollView>
    <androidx.constraintlayout.helper.widget.Flow
        android:id="@+id/flow"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:background="#FF0000"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
        />
</androidx.constraintlayout.widget.ConstraintLayout>

【问题讨论】:

    标签: android android-constraintlayout constraintlayout-flow


    【解决方案1】:

    您还没有将按钮添加到布局中。 Flow.addView 方法仅在它已经是相关 ConstraintLayout 的子对象时将其添加到帮助程序。

    来自documentation

    引用的视图必须是助手父级的子级。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多