Java tutorial
//package com.java2s; //License from project: Open Source License import android.app.Activity; import android.content.res.Configuration; import android.util.DisplayMetrics; public class Main { /** * Get the span count for a gridlayoutmanager for example. returns how many columns the * list of items should contain. * @param activity * @return The amount of columns the screen can fit */ public static int getSpanCount(Activity activity) { double diagonalInches = getDisplayInches(activity); int orientation = getDisplayOrientation(activity); if (diagonalInches >= 10) { if (orientation == Configuration.ORIENTATION_PORTRAIT) { return 3; } else { return 4; } } else if (diagonalInches >= 7) { if (orientation == Configuration.ORIENTATION_PORTRAIT) { return 2; } else { return 3; } } else { if (orientation == Configuration.ORIENTATION_PORTRAIT) { return 1; } else { return 1; } } } private static double getDisplayInches(Activity activity) { DisplayMetrics metrics = new DisplayMetrics(); activity.getWindowManager().getDefaultDisplay().getMetrics(metrics); int widthPixels = metrics.widthPixels; int heightPixels = metrics.heightPixels; float widthDpi = metrics.xdpi; float heightDpi = metrics.ydpi; float widthInches = widthPixels / widthDpi; float heightInches = heightPixels / heightDpi; double diagonalInches = Math.sqrt((widthInches * widthInches) + (heightInches * heightInches)); return diagonalInches; } private static int getDisplayOrientation(Activity activity) { return activity.getResources().getConfiguration().orientation; } }