最好的方法是使用 google 提供的 FlexboxLayout。
implementation 'com.google.android:flexbox:1.1.0'
implementation 'androidx.recyclerview:recyclerview:1.0.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
那么你必须遵循几个步骤。
1) 添加一个回收器视图,这是使用 flexbox 布局映射数据的最佳方式
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="0dp" />
2) 然后提供你自己的适配器
public class LinkedListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private final LayoutInflater mInflater;
private List<String> mItems = Collections.emptyList();
LinkedListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = mInflater.inflate(R.layout.my_layout_item, parent, false);
return new ViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
((ViewHolder)holder).updateWithItem(this.mItems.get(position), this.callback);
}
@Override
public int getItemCount() {
return mItems.size();
}
void setItems(List<String> items){
mItems = items;
notifyDataSetChanged();
}
class ViewHolder extends RecyclerView.ViewHolder{
private final TextView itemText;
private ViewHolder(View view) {
super(view);
itemText = view.findViewById(R.id.item);
}
public void updateWithItem(String item){
itemText.setText(item);
}
}
public List<String> getItems() {
return mItems;
}
}
3) 正如你现在所看到的,你应该有一些东西来定义你的布局,my_layout_item.xml 应该放在布局文件夹中
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:padding="15dp"
android:layout_margin="5dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
4) 现在,在您的片段或活动中,您必须链接所有这些内容。
myReclyclerView = view.findViewById(R.id.recycler_view);
FlexboxLayoutManager flexboxLayoutManager = new FlexboxLayoutManager(getActivity());
flexboxLayoutManager.setFlexDirection(FlexDirection.ROW);
flexboxLayoutManager.setJustifyContent(JustifyContent.CENTER);
flexboxLayoutManager.setFlexWrap(FlexWrap.WRAP);
myReclyclerView .setLayoutManager(flexboxLayoutManager);
List<String> items = new ArrayList<String>();
items.add("test");
myAdapter = new LinkedListAdapter (getContext());
myReclyclerView.setAdapter(myAdapter);
myAdapter.setItems(items);
我们来了,这对我来说是最好的解决方案。
来自 Kotlin 的来源:https://medium.com/gett-engineering/android-div-like-flexbox-layout-55f0e1286d66