Skip to content

Instantly share code, notes, and snippets.

@YuganshT79
Created March 16, 2018 11:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YuganshT79/62a3b41711abdd8768a87553af755676 to your computer and use it in GitHub Desktop.
Save YuganshT79/62a3b41711abdd8768a87553af755676 to your computer and use it in GitHub Desktop.
Dynamically change the Span of Grid Layout in Recycler View according to Screen size
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