Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Allows RecyclerView work like a FlowLayout.
public class MyActivity extends Activity {
public void onCreate(...){
RecyclerView rv = findViewByIdCast(R.id.rv);
// 2 is the number of columns
rv.setLayoutManager(new GridLayoutManager(this, 2));
// Calculates the width of the "CardView" dynamically.
int cardViewWidth = getResources().getDimension(R.dimen.my_cardview_width) + getResources().getDimension(R.dimen.my_cardview_margin) * 2;
rv.getViewTreeObserver().addOnGlobalLayoutListener(new OnFlowLayoutListener(rv, cardViewWidth));
}
}
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.ViewTreeObserver;
/**
* Allows RecyclerView work like a FlowLayout.
*
* Created by douglas on 16/09/15.
*/
public class OnFlowLayoutListener implements ViewTreeObserver.OnGlobalLayoutListener {
private final RecyclerView recyclerView;
private final float cardViewWidth;
public OnFlowLayoutListener(RecyclerView recyclerView, float cardViewWidth) {
this.recyclerView = recyclerView;
this.cardViewWidth = cardViewWidth;
}
@Override
public void onGlobalLayout() {
// recyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
int viewWidth = recyclerView.getMeasuredWidth();
int newSpanCount = (int) Math.floor(viewWidth / cardViewWidth);
if (newSpanCount > 0 && newSpanCount != ((GridLayoutManager) recyclerView.getLayoutManager()).getSpanCount()) {
((GridLayoutManager) recyclerView.getLayoutManager()).setSpanCount(newSpanCount);
recyclerView.requestLayout();
//recyclerView.getViewTreeObserver().addOnGlobalLayoutListener(this);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.