I have a RecyclerView adapter. Within the onBindViewHolder
, I check how many images each item passed to the adapter has. Depending on the number of images, I want to load/inflate a child layout into the main layout.
For example:
- If the item has 1 image, I need to inflate
images_one.xml
into the main layout - If the item has 2 images, I need to inflate
images_two.xml
into the main layout - etc, up to 8 images (
images_eight.xml
)
Here is the main layout, 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>
And here is one of the child layouts that need to be inflated into the main layout, 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>
And lastly, here is my RecyclerView adapter:
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();
}
}
What's the best way of implementing this?