Last active
October 11, 2018 19:47
-
-
Save douglasjunior/1644a14df51c9b62081e to your computer and use it in GitHub Desktop.
Allows RecyclerView work like a FlowLayout.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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