【发布时间】:2020-03-23 20:28:47
【问题描述】:
我们如何在androidx.constraintlayout.helper.widget.Flow中动态添加Views并动态添加引用ID。
【问题讨论】:
标签: android constraints android-constraintlayout
我们如何在androidx.constraintlayout.helper.widget.Flow中动态添加Views并动态添加引用ID。
【问题讨论】:
标签: android constraints android-constraintlayout
您应该首先将您的视图(带有 id 集)添加到父 ConstraintLayout。然后您可以使用Flow.addView() 将它的参考ID 添加到您的Flow。例如:
val view = LayoutInflater.from(context).inflate(R.layout.item, this, false)
view.layoutParams = ConstraintLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT)
view.id = View.generateViewId()
constraintLayout.addView(view)
flow.addView(view)
将此 xml 作为您的视图组:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/constraintLayout"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<androidx.constraintlayout.helper.widget.Flow
android:id="@+id/flow"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:flow_wrapMode="chain"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
【讨论】:
ViewCompat.generateViewId() 而不是 View.generateViewId()
这里是 Kotlin 实现
for (i in 0..4) {
val customView = CustomComponent (this)
customView.id = generateViewId()
constraintLayout.addView(customView,i)
flow.addView(customView)
}
下面是我的 XML
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/constraintLayout"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
>
<androidx.constraintlayout.helper.widget.Flow
android:id="@+id/flow"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:flow_wrapMode="chain"
app:flow_horizontalGap="2dp"
app:flow_verticalGap="2dp"
app:flow_verticalStyle = "spread_inside"
app:flow_horizontalStyle="packed"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
以下是我的自定义视图
class CustomComponent @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0,
defStyleRes: Int = 0):LinearLayout(context, attrs, defStyle, defStyleRes) {
init {
LayoutInflater.from(context)
.inflate(R.layout.custom_view, this, true)
}}
【讨论】:
view1.setId(View.generateViewId());
view2.setId(View.generateViewId());
view3.setId(View.generateViewId());
flow.setReferencedIds(new int[]{view1.getId(), view2.getId(), view3.getId()});
【讨论】: