【发布时间】:2015-11-20 00:07:37
【问题描述】:
我设置了一个典型的回收器适配器。适配器中的某些项目有图像,有时只有一个图像,有时是 20 个。我想创建一个图像拼贴,如下图所示,具体取决于每个项目中的图像数量:
我有 10 种不同的布局。第一个是在item只有1张图片时使用(布局中1个ImageView),另一个在item有2张图片时使用(布局中2个ImageViews),另一个在item有3张图片时使用,等等。如果该项目有超过 10 个图像,它使用 10 ImageViews 的布局并隐藏其余图像。布局命名为:
- one_image.xml
- two_images.xml
- three_images.xml
- ...等等...
这是我的 Recycler 适配器:
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private static Context context;
private List<Message> mDataset;
public RecyclerAdapter(Context context, List<Message> myDataset) {
this.context = context;
this.mDataset = myDataset;
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener, View.OnClickListener {
public TextView title;
public ViewHolder(View view) {
super(view);
view.setOnCreateContextMenuListener(this);
title = (TextView) view.findViewById(R.id.title);
}
}
@Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.message_layout, parent, false);
ViewHolder vh = new ViewHolder((LinearLayout) view);
return vh;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Message item = mDataset.get(position);
holder.title.setText(item.getTitle());
int numImages = item.getImages().size();
if (numImages > 0) {
// Show image collage
}
}
@Override
public int getItemCount() {
return mDataset.size();
}
}
这里是主要布局,message_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
// Image collage layout
</LinearLayout>
这是图像拼贴布局之一,two_images.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="@+id/image_one"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
/>
<ImageView
android:id="@+id/image_two"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
/>
</LinearLayout>
所以问题是,我如何根据图像数量加载/膨胀正确的布局到回收器适配器中,并用图像填充布局?
【问题讨论】:
-
你不会滚动你的布局吧?你最好写一个自定义的 ViewGroup
-
滚动是什么意思?从回收器适配器加载项目的主要布局滚动(它是一张卡片列表)。
-
应该向哪个方向滚动?在这种情况下,您应该考虑 StaggeredGridLayoutManager(请参阅@Amit Kumar 的回答)
-
图片拼贴本身不能滚动。
-
在这种情况下,请考虑以下库:github.com/blazsolar/FlowLayout 或 github.com/ApmeM/android-flowlayout。要获得完美的阵容,您仍然需要一些自我定制。
标签: android android-layout android-activity android-xml