Skip to content

Instantly share code, notes, and snippets.

@douglasjunior
Last active October 11, 2018 19:47
Show Gist options
  • Save douglasjunior/1644a14df51c9b62081e to your computer and use it in GitHub Desktop.
Save douglasjunior/1644a14df51c9b62081e to your computer and use it in GitHub Desktop.
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