Skip to content

Instantly share code, notes, and snippets.

@mtsahakis
Last active April 25, 2021 22:40
Show Gist options
  • Save mtsahakis/33085460b9707fdf0729 to your computer and use it in GitHub Desktop.
Save mtsahakis/33085460b9707fdf0729 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