Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

smallestScreenWidthDp for pre-3.2 devices?

From reading the documentation for supporting multiple screen sizes, starting with Android 3.2, you can use smallestScreenWidthDp to conditionally set a layout, but is there anything for pre-3.2 devices?

I have a fragment-based layout, and I'd like to show both fragments on the screen if the screen size is greater than 600dp.

This is the code I'm using to set the fragments that I'd like find an alternative for:

public class MyActivity extends FragmentActivity  
{
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        if (getResources().getConfiguration().smallestScreenWidthDp >= 600) {
            finish();
            return;
        }

        if (savedInstanceState == null) {
            final DetailFragment details = new DetailFragment();
            details.setArguments(getIntent().getExtras());

            getSupportFragmentManager().beginTransaction().add(android.R.id.content, details).commit();
        }
    }
}
like image 721
Kris B Avatar asked May 17 '26 17:05

Kris B


1 Answers

Here's what I use:

public static int getSmallestScreenWidthDp(Context context) {
    Resources resources = context.getResources();
    try {
        Field field = Configuration.class.getDeclaredField("smallestScreenWidthDp");
        return (Integer) field.get(resources.getConfiguration());
    } catch (Exception e) {
        // not perfect because reported screen size might not include status and button bars
        DisplayMetrics displayMetrics = resources.getDisplayMetrics();
        int smallestScreenWidthPixels = Math.min(displayMetrics.widthPixels, displayMetrics.heightPixels);
        return Math.round(smallestScreenWidthPixels / displayMetrics.density);
    }
}

Unfortunately it is not perfect since the screen size in DisplayMetrics might not include the status bar or soft buttons.

For example on my Galaxy Tab 10.1 the actual value is 800 whereas the computed value is only 752.

like image 150
devconsole Avatar answered May 20 '26 06:05

devconsole



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!