在Android中检查屏幕大小的简便方法是什么?

时间:2014-07-22 05:43:07

标签: android android-layout android-intent

我需要能够为Android上的平板电脑提供不同的手机用户界面。但是我一直想知道一种简单,直接的方法来对屏幕尺寸/分辨率进行运行时检查。我搜索了很多,我得到的所有答案都告诉我屏幕密度,这不是我想要的,或者属于“使用dp”或“在可绘制文件夹中放置不同的图像”的类别。这些都不能满足我的需要。我在StackOverflow上看到的所有答案都属于上述类别,或者已经弃用了解决方案。

我以为我有一个可行的解决方案:

Configuration configuration = getResources().getConfiguration();
boolean bigScreen = configuration.screenLayout == configuration.SCREENLAYOUT_SIZE_LARGE
    || configuration.screenLayout == configuration.SCREENLAYOUT_SIZE_XLARGE;

if(bigScreen)
{
    Intent userCreationIntent = new Intent(getApplicationContext(), AboutUs.class);
    startActivityForResult(userCreationIntent, 0);
}
else
{
    Intent userCreationIntent = new Intent(getApplicationContext(),AboutUsSmall.class);
    startActivityForResult(userCreationIntent,0);
}

问题是此代码还将我的Nexus 7(7英寸平板电脑)发送到AboutUsSmall布局/类。

我做错了什么?更重要的是,我该怎么做呢?

3 个答案:

答案 0 :(得分:3)

将其更改为:

public static boolean isLargeScreen(Context context)
{
    return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK)
            >= Configuration.SCREENLAYOUT_SIZE_LARGE;
}

对于Nexus 7.change SCREENLAYOUT_SIZE_XLARGE返回SCREENLAYOUT_SIZE_LARGE

,返回true

答案 1 :(得分:1)

我猜你有充分的理由避免android standard for different screen sizes。我相信Arash有更清洁的解决方案,但这是另一个解决方案,可能更好地回答你在标题中提出的问题:

DisplayMetrics dm = getResources().getDisplayMetrics();

double density = dm.density * 160;
double x = Math.pow(dm.widthPixels / density, 2);
double y = Math.pow(dm.heightPixels / density, 2);
double screenInches = Math.sqrt(x + y);
log.info("inches: {}", screenInches);

Thisthis帖子解释得非常好。祝你好运!

答案 2 :(得分:0)

对于不同的屏幕尺寸,以下是应用程序中的资源目录列表,它为不同的屏幕尺寸提供不同的布局设计,为小,中,高和超高密度屏幕提供不同的位图可绘制。您可以在res文件夹中使用不同大小的布局文件,也可以根据密度对可绘制图像进行更改。

res/layout/my_layout.xml             // layout for normal screen size ("default")
  res/layout-small/my_layout.xml       // layout for small screen size
  res/layout-large/my_layout.xml       // layout for large screen size
  res/layout-xlarge/my_layout.xml      // layout for extra large screen size
  res/layout-xlarge-land/my_layout.xml // layout for extra large in landscape orientation

Android会自动打开与屏幕尺寸对应的特定布局。 您可以查看有关多屏here

的开发者网站