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();
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With