From the description, it's difficult to tell exactly which direction the scroll behaviour should occur but the following should give you an idea of what to do:
You can nest a RecyclerView
as an item inside your RecyclerView
.
In the onCreateViewHolder
method of your Adapter, return an alternative ViewHolder
depending on the provided viewType
. For brevity, I've done this as a switch
statement.
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case REGULAR_ITEM:
return new RegularItemViewHolder(getRowView(parent, R.layout.list_item_regular);
case NESTED_LIST_TYPE:
return new NestedRecyclerViewHolder(getRowView(parent, R.layout.list_item_nested_recycler);
...
}
protected View getRowView(ViewGroup parent, @LayoutRes final int layoutRes) {
return layoutInflater.inflate(layoutRes, parent, false);
}
ViewHolder
public class NestedRecyclerViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.my_nested_recyclerview)
public RecyclerView recyclerView;
public NestedRecyclerViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
Then in onBindViewHolder
you can setup this nested RecyclerView
with a horizontal LinearLayoutManager
(This is assuming you have a vertical parent RecyclerView
within which you'd like one or more of the rows to be a horizontal RecyclerView
).
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
// find the item type based on the position
if(rowType == NESTED_LIST_TYPE) {
NestedRecyclerViewHolder viewHolder = (NestedRecyclerViewHolder)holder;
viewHolder.recyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
viewHolder.recyclerView.setAdapter(new MyAdapter());
// continue to set up the nested `RecyclerView` as you would a regular one
}
...
This will provide the horizontal scrolling behaviour in a vertical RecyclerView
- of course you can flip these to work in the other way around by using different LinearLayoutManager
s for each of the RecyclerView
s.
To make it behave like a ViewPager
, you'd need to use the SnapHelper
as you alluded to in your question:
- Set the width of the list items in the nested
RecyclerView
's Adapter to match_parent
(do this in the XML layout for the items).
Initialise a LinearSnapHelper
(Support library 24.1) like this:
SnapHelper snapHelper = new LinearSnapHelper();
snapHelper.attachToRecyclerView(viewHolder.recyclerView);
This will give you the behaviour where the user can only see one item at a time and allow the user to page through individual horizontal views.