android瀑布流布局代码
时间: 2023-12-01 19:04:35 浏览: 126
Android中可以使用RecyclerView和GridLayoutManager来实现瀑布流布局,以下是示例代码:
1.在布局文件中添加RecyclerView控件:
```
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp" />
```
2.在Activity或Fragment中初始化RecyclerView和GridLayoutManager,并设置Adapter:
```
// 初始化RecyclerView
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
// 设置Adapter
MyAdapter adapter = new MyAdapter(this, data);
recyclerView.setAdapter(adapter);
```
3.自定义Adapter,并在ViewHolder中设置图片宽高:
```
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private Context mContext;
private List<String> mData;
public MyAdapter(Context context, List<String> data) {
mContext = context;
mData = data;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item_layout, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
String imageUrl = mData.get(position);
// 加载图片,这里使用了Glide库
Glide.with(mContext).load(imageUrl).into(holder.imageView);
// 设置图片宽高
ViewGroup.LayoutParams layoutParams = holder.imageView.getLayoutParams();
layoutParams.height = getRandomHeight();
holder.imageView.setLayoutParams(layoutParams);
}
@Override
public int getItemCount() {
return mData.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
public ViewHolder(@NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.image_view);
}
}
// 获取随机高度
private int getRandomHeight() {
return (int) (Math.random() * 300 + 200);
}
}
```
4.item_layout布局文件中只需要添加一个ImageView即可:
```
<ImageView
android:id="@+id/image_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="centerCrop" />
```
以上就是实现Android瀑布流布局的基本代码,可以根据自己的需求进行修改和扩展。
阅读全文