我已经在现有问题中看到了将按钮添加到 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>