【发布时间】:2015-11-21 23:16:25
【问题描述】:
我有一个 RecyclerView 适配器。在onBindViewHolder 中,我检查传递给适配器的每个项目有多少图像。根据图像的数量,我想将子布局加载/膨胀到主布局中。
例如:
- 如果项目有 1 张图片,我需要将
images_one.xml填充到主布局中 - 如果项目有 2 张图片,我需要将
images_two.xml填充到主布局中 - 等,最多 8 张图片 (
images_eight.xml)
这里是主要布局,main_layout.xml:
<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"
/>
// INFLATE CHILD LAYOUT HERE (images_one.xml, images_two.xml, etc.)
<TextView
android:id="@+id/desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
这里是需要膨胀到主布局中的子布局之一,images_two.xml:
<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"
/>
<ImageView
android:id="@+id/image_two"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
最后,这是我的 RecyclerView 适配器:
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 TextView desc;
public ViewHolder(View view) {
super(view);
view.setOnCreateContextMenuListener(this);
title = (TextView) view.findViewById(R.id.title);
desc = (TextView) view.findViewById(R.id.desc);
}
}
@Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.main_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());
holder.desc.setText(item.getDesc());
int numImages = item.getImages().size();
if (numImages == 1) {
// Inflate images_one.xml into main_layout.xml
} else if (numImages == 2) {
// Inflate images_two.xml into main_layout.xml
} else if (numImages == 3) {
// Inflate images_three.xml into main_layout.xml
}
// ETC...
}
@Override
public int getItemCount() {
return mDataset.size();
}
}
实现这一点的最佳方式是什么?
【问题讨论】:
-
如何在 RecyclerView 适配器中实现?
-
将它充气到您的 ViewHolder 中的 itemView 中。
-
如果我在 ViewHolder 中给它充气,我无法检查该项目有多少张图片。
-
onBindViewHolder(ViewHolder holder, int position)中的持有者
标签: android android-layout android-activity android-xml android-recyclerview