Skip to content

Instantly share code, notes, and snippets.

@mohamedmohamedtaha
Forked from mtsahakis/GridFragment.java
Created July 12, 2020 18:15
Show Gist options
  • Save mohamedmohamedtaha/62b4f5ac8e9f18ed61109941f48bb947 to your computer and use it in GitHub Desktop.
Save mohamedmohamedtaha/62b4f5ac8e9f18ed61109941f48bb947 to your computer and use it in GitHub Desktop.
Dynamically set span count in an Android RecyclerView's GridLayoutManager. Implementation is taken from a Fragment.
private RecyclerView mRecyclerView;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_view, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
// ommiting other recycler view set up, such as adapter and Layout manager set up ..
ViewTreeObserver viewTreeObserver = mRecyclerView.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
calculateCellSize();
}
});
}
private static final int sColumnWidth = 120; // assume cell width of 120dp
private void calculateSize() {
int spanCount = (int) Math.floor(mRecyclerView.getWidth() / convertDPToPixels(sColumnWidth));
((GridLayoutManager) mRecyclerView.getLayoutManager()).setSpanCount(spanCount);
}
private float convertDPToPixels(int dp) {
DisplayMetrics metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
float logicalDensity = metrics.density;
return dp * logicalDensity;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment