How to center the last two items of a RecyclerView
with 3 columns ?.
Example with 5 items:
1 item | 2 item | 3 item
4 item | 5 item
Image to explain
I was in the same situation and I found something very interesting: FlowLayout.
I found this library and it is really easy to use, here are the instructions: https://github.com/ApmeM/android-flowlayout. It centers the elements automatically!
For example, in my case, after add the library in the gradle using this: compile 'org.apmem.tools:layouts:1.10@aar', I changed the RecyclerView element for this:
<org.apmem.tools.layouts.FlowLayout
android:id="@+id/lytXXXXX"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layoutDirection="ltr" (Left to right)
android:orientation="horizontal" />
After change it, I created the method loadElementsToTheFlowLayout(). Here it is:
private void loadElementsToTheFlowLayout() {
// Remove all the FlowLayout elements
flowLayout.removeAllViews();
// For each element, I create its view and I add it to the FlowLayout
for (final Element e : elementsList) {
// Inflate the e view to the flow layout
View viewElement = layoutInflater.inflate(R.layout.elements_item, flowLayout, false);
// Create the element view with its data
FrameLayout elementView = (FrameLayout) viewElement .findViewById(R.id.lytForElement);
TextViewFont txtLine0 = (TextViewFont) viewElement .findViewById(R.id.txtLine0);
txtLine0.setText(e.getLine0());
TextViewFont txtLine1 = (TextViewFont) viewElement .findViewById(R.id.txtLine1);
txtLine1.setText(e.getLine1());
TextViewFont txtLine2 = (TextViewFont) viewElement .findViewById(R.id.txtLine2);
txtLine2.setText(e.getLine2());
TextViewFont txtLine3 = (TextViewFont) viewElement .findViewById(R.id.txtLine3);
txtLine3.setText(e.getLine3());
// Add the view to the FlowLayout
flowLayout.addView(viewElement );
}
}
Hope it helps!
You could use a GridLayoutManager
on your RecyclerView
. The setSpanSizeLookup()
lets you custom the the span size for each of your RecyclerView
's rows. You just have to override the getSpanSize(int position)
method.
You could do something like this:
int lastRowIndex = Math.ceil(yourList.length / numberOfColumns);
GridLayoutManager manager = new GridLayoutManager(context, 2); // MAX NUMBER OF SPACES
manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
if (position == lastRowIndex)
return 2;
else
return 3;
}
});
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