I'm trying to implement a RecyclerView
like a UICollectionView
in iOS.
I want to set a contentInset
at the bottom of the recycler view but I can't find an option to do it.
Is there something similar for Android?
Solution is simple:
<android.support.v7.widget.RecyclerView
android:paddingBottom="30dp"
android:clipToPadding="false"
android:layout_width="match_parent"
android:layout_height="match_parent" />
You can create your own ItemDecoration and set there a offset for the first item and also margins between the items.
Here is my code for my horizontal scrolling recyclerview.
public class HorizontalContentItemDecoration extends RecyclerView.ItemDecoration {
private int startOffset = 10;
private int itemOffset = 10;
public HorizontalContentItemDecoration(int startOffset, int itemOffset) {
this.startOffset = startOffset;
this.itemOffset = itemOffset;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view);
if (position == 0) {
outRect.set(startOffset, 0, itemOffset, 0);
} else {
outRect.set(0, 0, itemOffset, 0);
}
}
}
I have created a wrapper adapter to achieve this, which isolates the code nicely. But, I would like a better solution..
public class HeaderSpaceWrapperAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_HEADER = 0x4711;
private int mSpace;
RecyclerView.Adapter mAdapter;
public HeaderSpaceWrapperAdapter(RecyclerView.Adapter adapter, int space) {
mAdapter = adapter;
mSpace = space;
mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
@Override
public void onChanged() {
notifyDataSetChanged();
}
});
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == TYPE_HEADER) {
return new ViewHolder(new Spacer(parent.getContext(), mSpace));
}
return mAdapter.onCreateViewHolder(parent, viewType);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (position > 0) {
mAdapter.onBindViewHolder(holder, position - 1);
}
}
@Override
public int getItemCount() {
return 1 + mAdapter.getItemCount();
}
@Override
public int getItemViewType(int position) {
return position == 0 ? TYPE_HEADER : mAdapter.getItemViewType(position - 1);
}
private class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(View view) {
super(view);
}
}
}
Then use it:
mWrapperAdapter = new HeaderSpaceWrapperAdapter(mAdapter, 100);
mRecyclerView.setAdapter(mWrapperAdapter);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With