在Android中實(shí)現(xiàn)瀑布流布局可以使用RecyclerView和GridLayoutManager來(lái)實(shí)現(xiàn)。以下是一個(gè)簡(jiǎn)單的示例代碼:
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
RecyclerView recyclerView = findViewById(R.id.recycler_view);
GridLayoutManager layoutManager = new GridLayoutManager(this, 2); //設(shè)置列數(shù)為2
recyclerView.setLayoutManager(layoutManager);
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private List<String> dataList;
public MyAdapter(List<String> dataList) {
this.dataList = dataList;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
holder.bindData(dataList.get(position));
}
@Override
public int getItemCount() {
return dataList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
private TextView textView;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.text_view);
}
public void bindData(String data) {
textView.setText(data);
}
}
}
<TextView
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp" />
List<String> dataList = new ArrayList<>();
for (int i = 0; i < 20; i++) {
dataList.add("Item " + i);
}
MyAdapter adapter = new MyAdapter(dataList);
recyclerView.setAdapter(adapter);
通過(guò)以上步驟,就可以實(shí)現(xiàn)一個(gè)簡(jiǎn)單的Android瀑布流布局??梢愿鶕?jù)實(shí)際需求自定義樣式和布局方式。