Android fluid layout implementation
1、FlexboxLayout
FlexboxLayout is a powerful control open sourced by Google, which directly inherits from ViewGroup.
dependencies {
implementation 'com.google.android.flexbox:flexbox:3.0.0'
}
<com.google.android.flexbox.FlexboxLayout
android:id="@+id/fl_content"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
var flContent = findViewById<FlexboxLayout>(R.id.fl_content)
flContent.flexWrap = FlexWrap.WRAP
flContent.flexDirection = FlexDirection.ROW
map.keys?.forEach {
flContent.layoutInflate(R.layout.item_filter).apply {
var tvName = this.findViewById<TextView>(R.id.tv_name)
tvName.text = it
tag = false
flContent.addView(this)
}
}
2、Recyclerview+FlexboxLayoutManager
implementation 'com.google.android:flexbox:3.0.0'//Android官方流式布局
FlexboxLayoutManager layoutManager=new FlexboxLayoutManager(this);
layoutManager.setFlexDirection(FlexDirection.ROW);
//layoutManager.setJustifyContent(JustifyContent.CENTER);
//layoutManager.setAlignItems(AlignItems.CENTER);
recyclerview.setLayoutManager(layoutManager);
recyclerview.setAdapter(adapter);
3、ConstraintLayout + Flow
Constraintlayout 2.0 has added Flow flow virtual layout.
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
<androidx.constraintlayout.helper.widget.Flow
android:id="@+id/flow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:constraint_referenced_ids="tvA,tvB,tvC,tvD,tvE,tvF,tvG"
app:flow_horizontalGap="30dp" //View水平间隔
app:flow_verticalGap="30dp" //垂直间隔
app:flow_wrapMode="none"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
for (i in 0..4) {
val customView = CustomComponent (this)
customView.id = generateViewId()
constraintLayout.addView(customView,i)
flow.addView(customView)
}