Skip to content

Instantly share code, notes, and snippets.

@geniushkg
Created June 24, 2016 05:22
Show Gist options
  • Save geniushkg/11cd41c3761427aa2cf1bfb822a74583 to your computer and use it in GitHub Desktop.
Save geniushkg/11cd41c3761427aa2cf1bfb822a74583 to your computer and use it in GitHub Desktop.
A simple method helper for grid in android to be dynamic in number of columns
public int numOfColumnsForOrientation() {
Display display = getActivity().getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
int numOfColoums = 0;
if (width < height) {
// portrait mode
numOfColoums = 2;
if (width > 600) { // for tablet sw600
numOfColoums = 3;
}
} else {
// landscape mode
numOfColoums = 3;
if (width > 600) { // for tablet sw600
numOfColoums = 3;
}
}
return numOfColoums;
}
@kosratdev
Copy link

kosratdev commented Jun 24, 2016

on portrait mode in nexus 5x shows 3 col??

the solution is (calculate width and height in dp) look at the following code

DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
float dpHeight = displayMetrics.heightPixels / displayMetrics.density;
float dpWidth = displayMetrics.widthPixels / displayMetrics.density;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment