Respostas:
Você pode usar a Configuration.screenLayout
máscara de bits.
Exemplo:
if ((getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK) ==
Configuration.SCREENLAYOUT_SIZE_LARGE) {
// on a large screen device ...
}
O código abaixo exibe a resposta acima, exibindo o tamanho da tela como um Toast.
//Determine screen size
if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) {
Toast.makeText(this, "Large screen", Toast.LENGTH_LONG).show();
}
else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) {
Toast.makeText(this, "Normal sized screen", Toast.LENGTH_LONG).show();
}
else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_SMALL) {
Toast.makeText(this, "Small sized screen", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(this, "Screen size is neither large, normal or small", Toast.LENGTH_LONG).show();
}
Este código abaixo exibe a densidade da tela como um brinde.
//Determine density
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int density = metrics.densityDpi;
if (density == DisplayMetrics.DENSITY_HIGH) {
Toast.makeText(this, "DENSITY_HIGH... Density is " + String.valueOf(density), Toast.LENGTH_LONG).show();
}
else if (density == DisplayMetrics.DENSITY_MEDIUM) {
Toast.makeText(this, "DENSITY_MEDIUM... Density is " + String.valueOf(density), Toast.LENGTH_LONG).show();
}
else if (density == DisplayMetrics.DENSITY_LOW) {
Toast.makeText(this, "DENSITY_LOW... Density is " + String.valueOf(density), Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(this, "Density is neither HIGH, MEDIUM OR LOW. Density is " + String.valueOf(density), Toast.LENGTH_LONG).show();
}
A resposta de Jeff Gilfelt como método auxiliar estático:
private static String getSizeName(Context context) {
int screenLayout = context.getResources().getConfiguration().screenLayout;
screenLayout &= Configuration.SCREENLAYOUT_SIZE_MASK;
switch (screenLayout) {
case Configuration.SCREENLAYOUT_SIZE_SMALL:
return "small";
case Configuration.SCREENLAYOUT_SIZE_NORMAL:
return "normal";
case Configuration.SCREENLAYOUT_SIZE_LARGE:
return "large";
case 4: // Configuration.SCREENLAYOUT_SIZE_XLARGE is API >= 9
return "xlarge";
default:
return "undefined";
}
}
private String getDeviceDensity() {
int density = mContext.getResources().getDisplayMetrics().densityDpi;
switch (density)
{
case DisplayMetrics.DENSITY_MEDIUM:
return "MDPI";
case DisplayMetrics.DENSITY_HIGH:
return "HDPI";
case DisplayMetrics.DENSITY_LOW:
return "LDPI";
case DisplayMetrics.DENSITY_XHIGH:
return "XHDPI";
case DisplayMetrics.DENSITY_TV:
return "TV";
case DisplayMetrics.DENSITY_XXHIGH:
return "XXHDPI";
case DisplayMetrics.DENSITY_XXXHIGH:
return "XXXHDPI";
default:
return "Unknown";
}
}
Obrigado pelas respostas acima, que me ajudaram muito :-) Mas para aqueles (como eu) obrigados a ainda suportar o Android 1.5, podemos usar a reflexão de java para compatibilidade retroativa:
Configuration conf = getResources().getConfiguration();
int screenLayout = 1; // application default behavior
try {
Field field = conf.getClass().getDeclaredField("screenLayout");
screenLayout = field.getInt(conf);
} catch (Exception e) {
// NoSuchFieldException or related stuff
}
// Configuration.SCREENLAYOUT_SIZE_MASK == 15
int screenType = screenLayout & 15;
// Configuration.SCREENLAYOUT_SIZE_SMALL == 1
// Configuration.SCREENLAYOUT_SIZE_NORMAL == 2
// Configuration.SCREENLAYOUT_SIZE_LARGE == 3
// Configuration.SCREENLAYOUT_SIZE_XLARGE == 4
if (screenType == 1) {
...
} else if (screenType == 2) {
...
} else if (screenType == 3) {
...
} else if (screenType == 4) {
...
} else { // undefined
...
}
Configuration
classe. Esses são valores finais estáticos que serão incorporados no momento da compilação (ou seja, serão substituídos pelos valores reais), para que seu código não seja quebrado nas versões mais antigas da plataforma.
targetSdkVersion
último lançamento.
Se você deseja conhecer facilmente a densidade e o tamanho da tela de um dispositivo Android, pode usar este aplicativo gratuito (sem permissão): https://market.android.com/details?id=com.jotabout.screeninfo
Precisa verificar telas grandes e densidades altas? Este é o código alterado da resposta escolhida.
//Determine screen size
if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) {
Toast.makeText(this, "Large screen",Toast.LENGTH_LONG).show();
} else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) {
Toast.makeText(this, "Normal sized screen" , Toast.LENGTH_LONG).show();
} else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_SMALL) {
Toast.makeText(this, "Small sized screen" , Toast.LENGTH_LONG).show();
} else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE) {
Toast.makeText(this, "XLarge sized screen" , Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Screen size is neither large, normal or small" , Toast.LENGTH_LONG).show();
}
//Determine density
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int density = metrics.densityDpi;
if (density==DisplayMetrics.DENSITY_HIGH) {
Toast.makeText(this, "DENSITY_HIGH... Density is " + String.valueOf(density), Toast.LENGTH_LONG).show();
} else if (density==DisplayMetrics.DENSITY_MEDIUM) {
Toast.makeText(this, "DENSITY_MEDIUM... Density is " + String.valueOf(density), Toast.LENGTH_LONG).show();
} else if (density==DisplayMetrics.DENSITY_LOW) {
Toast.makeText(this, "DENSITY_LOW... Density is " + String.valueOf(density), Toast.LENGTH_LONG).show();
} else if (density==DisplayMetrics.DENSITY_XHIGH) {
Toast.makeText(this, "DENSITY_XHIGH... Density is " + String.valueOf(density), Toast.LENGTH_LONG).show();
} else if (density==DisplayMetrics.DENSITY_XXHIGH) {
Toast.makeText(this, "DENSITY_XXHIGH... Density is " + String.valueOf(density), Toast.LENGTH_LONG).show();
} else if (density==DisplayMetrics.DENSITY_XXXHIGH) {
Toast.makeText(this, "DENSITY_XXXHIGH... Density is " + String.valueOf(density), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Density is neither HIGH, MEDIUM OR LOW. Density is " + String.valueOf(density), Toast.LENGTH_LONG).show();
}
Aqui está uma versão Xamarin.Android da resposta de Tom McFarlin
//Determine screen size
if ((Application.Context.Resources.Configuration.ScreenLayout & ScreenLayout.SizeMask) == ScreenLayout.SizeLarge) {
Toast.MakeText (this, "Large screen", ToastLength.Short).Show ();
} else if ((Application.Context.Resources.Configuration.ScreenLayout & ScreenLayout.SizeMask) == ScreenLayout.SizeNormal) {
Toast.MakeText (this, "Normal screen", ToastLength.Short).Show ();
} else if ((Application.Context.Resources.Configuration.ScreenLayout & ScreenLayout.SizeMask) == ScreenLayout.SizeSmall) {
Toast.MakeText (this, "Small screen", ToastLength.Short).Show ();
} else if ((Application.Context.Resources.Configuration.ScreenLayout & ScreenLayout.SizeMask) == ScreenLayout.SizeXlarge) {
Toast.MakeText (this, "XLarge screen", ToastLength.Short).Show ();
} else {
Toast.MakeText (this, "Screen size is neither large, normal or small", ToastLength.Short).Show ();
}
//Determine density
DisplayMetrics metrics = new DisplayMetrics();
WindowManager.DefaultDisplay.GetMetrics (metrics);
var density = metrics.DensityDpi;
if (density == DisplayMetricsDensity.High) {
Toast.MakeText (this, "DENSITY_HIGH... Density is " + density, ToastLength.Long).Show ();
} else if (density == DisplayMetricsDensity.Medium) {
Toast.MakeText (this, "DENSITY_MEDIUM... Density is " + density, ToastLength.Long).Show ();
} else if (density == DisplayMetricsDensity.Low) {
Toast.MakeText (this, "DENSITY_LOW... Density is " + density, ToastLength.Long).Show ();
} else if (density == DisplayMetricsDensity.Xhigh) {
Toast.MakeText (this, "DENSITY_XHIGH... Density is " + density, ToastLength.Long).Show ();
} else if (density == DisplayMetricsDensity.Xxhigh) {
Toast.MakeText (this, "DENSITY_XXHIGH... Density is " + density, ToastLength.Long).Show ();
} else if (density == DisplayMetricsDensity.Xxxhigh) {
Toast.MakeText (this, "DENSITY_XXXHIGH... Density is " + density, ToastLength.Long).Show ();
} else {
Toast.MakeText (this, "Density is neither HIGH, MEDIUM OR LOW. Density is " + density, ToastLength.Long).Show ();
}
Tente esta função isLayoutSizeAtLeast (int screenSize)
Para verificar a tela pequena, pelo menos 320x426 dp e acima de getResources (). GetConfiguration (). IsLayoutSizeAtLeast (Configuration.SCREENLAYOUT_SIZE_SMALL);
Para verificar a tela normal, pelo menos 320 x 480 dp e acima, getResources (). GetConfiguration (). IsLayoutSizeAtLeast (Configuration.SCREENLAYOUT_SIZE_NORMAL);
Para verificar a tela grande, pelo menos 480 x 640 dp e acima, getResources (). GetConfiguration (). IsLayoutSizeAtLeast (Configuration.SCREENLAYOUT_SIZE_LARGE);
Para verificar uma tela extra grande, pelo menos 720x960 dp e acima de getResources (). GetConfiguration (). IsLayoutSizeAtLeast (Configuration.SCREENLAYOUT_SIZE_XLARGE);
Em 2018, se você precisar da resposta de Jeff em Kotlin, aqui está:
private fun determineScreenSize(): String {
// Thanks to https://stackoverflow.com/a/5016350/2563009.
val screenLayout = resources.configuration.screenLayout
return when {
screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK == Configuration.SCREENLAYOUT_SIZE_SMALL -> "Small"
screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK == Configuration.SCREENLAYOUT_SIZE_NORMAL -> "Normal"
screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK == Configuration.SCREENLAYOUT_SIZE_LARGE -> "Large"
screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK == Configuration.SCREENLAYOUT_SIZE_XLARGE -> "Xlarge"
screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK == Configuration.SCREENLAYOUT_SIZE_UNDEFINED -> "Undefined"
else -> error("Unknown screenLayout: $screenLayout")
}
}
Você não poderia fazer isso usando um recurso de string e enumerações? Você pode definir um recurso de sequência que tenha o nome do tamanho da tela, como SMALL, MEDIUM ou LARGE. Em seguida, você pode usar o valor do recurso de cadeia de caracteres para criar uma instância do enum.
Defina um Enum no seu código para os diferentes tamanhos de tela de sua preferência.
public Enum ScreenSize {
SMALL,
MEDIUM,
LARGE,;
}
Defina um recurso de sequência, por exemplo, tamanho da tela, cujo valor será SMALL, MEDIUM ou LARGE.
<string name="screensize">MEDIUM</string>
screensize
em um recurso de sequência em cada dimensão com a qual você se preocupa. <string name="screensize">MEDIUM</string>
iria em values-sw600dp / strings.xml e values-medium / strings.xml e <string name="screensize">LARGE</string>
em sw720dp / strings.xml e valores-large / strings.xml.ScreenSize size = ScreenSize.valueOf(getReources().getString(R.string.screensize);
Copie e cole esse código no seu Activity
e, quando executado, será Toast
a categoria de tamanho da tela do dispositivo.
int screenSize = getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK;
String toastMsg;
switch(screenSize) {
case Configuration.SCREENLAYOUT_SIZE_LARGE:
toastMsg = "Large screen";
break;
case Configuration.SCREENLAYOUT_SIZE_NORMAL:
toastMsg = "Normal screen";
break;
case Configuration.SCREENLAYOUT_SIZE_SMALL:
toastMsg = "Small screen";
break;
default:
toastMsg = "Screen size is neither large, normal or small";
}
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();