3

On Android API 16 (4.1 Jelly Bean) and later we have the method getCurrentSizeRange to get the range of width and height. How do I get the size range on versions earlier than 4.1?

I tried to look into the source code to see how the range is computed. It is done differently on different Android versions and I couldn't find the logic which computes these sizes. Any pointers that could help me find this is much appreciated.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
500865
  • 6,920
  • 7
  • 44
  • 87

1 Answers1

1

If you're just trying to determine the heights and widths for portrait and landscape, you could just quickly force the orientation both ways and get the metrics each way. The following snippet does that. The code is guarded by a simple preference check since I tested this in onCreate() and the orientation changes will cause an activity restart (and go into a loop). In your app, you'll probably want to do something more specific. Also, all of the methods used are valid down to API 1, but may have been replaced or renamed in higher versions.

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (prefs.getBoolean("firstTime", true)) {
    prefs.edit().putBoolean("firstTime", false).commit();

    DisplayMetrics dm = new DisplayMetrics();

    setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    Log.e(TAG, String.format("landscape is %d x %d",  dm.widthPixels, dm.heightPixels));
    // Do something with the values, perhaps saving them in prefs

    setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    Log.e(TAG, String.format("portrait is %d x %d",  dm.widthPixels, dm.heightPixels));
    // Do something with the values, perhaps saving them in prefs
}
scottt
  • 8,301
  • 1
  • 31
  • 41
  • Scott : Heights and widths are different from currentSizeRange in 4.1. Take a look at the documentation of getCurrentSizeRange and you will get an idea. – 500865 Sep 15 '14 at 19:11
  • Yes, that's correct. Depending on what you want to do with the values, you'll still need to analyze the values returned from getMetrics() and determine the smallest and largest widths and the heights. It's admittedly not an ideal solution, but supporting older API versions is never without hassles. – scottt Sep 15 '14 at 19:37