如何让我的应用在所有设备中看起来都一样?

时间:2015-02-19 17:37:49

标签: android layout screen-orientation screen-size android-screen-support

我刚接触Android开发,我在android studio上构建了一个应用程序,我想让我的应用程序在所有设备上都有相同的设计:

  

三星Galaxy S4 => 1080x1290; 5.0”

Galaxy Nexus => 720x1280; 4.7”

Nexus 4 => 768x1280; 4.7”

Motorola Droid Razr M => 540x960; 4.3”

Nexus S => 480x800; 4”

Galaxy S2 => 480x800; 4.3”

Galaxy Ace => 320x480; 3.5”

Galaxy Note => 800x1280; 5.3”

Galaxy Note II => 720x1280; 5.5”

Nexus 10 => 2560 x 1600; 10.1”

Galaxy Tab 10.1 => 1280 * 800; 10.1”

Galaxy Note 8.0 => 1280 * 800; 8.0”

Galaxy Tab 7.7 => 1280 * 800; 7.7”

Nexus 7 => 1280 * 800; 7.0”

Galaxy Tab => 1024 * 600; 7.0”


我在这里阅读了很多问题

http://developer.android.com/training/multiscreen/index.html

http://developer.android.com/guide/practices/screens_support.html#DeclaringTabletLayouts

我在" dp"中使用了宽度/高度并使用所有项目

android:layout_margin
android:paddingLeft
android:paddingRight
android:paddingTop
android:paddingBottom

它工作正常,但我知道有一种方法可以读取设备屏幕,然后决定在应用程序中打开哪个布局,假设我有一个布局,我有这些尺寸

  

res / layout / main_activity.xml#适用于手机(可用宽度小于600dp)   res / layout-sw600dp / main_activity.xml#适用于7“平板电脑(600dp宽大)   res / layout-sw720dp / main_activity.xml#适用于10英寸平板电脑(720dp宽大)


我的问题是:我如何编写我的java活动来读取我的应用程序在其上运行的设备屏幕,然后决定打开哪个布局就像设备是S2然后java做这样的事情:

if (tabletDeviceSize) {

//use tablet support layout

} else

{

//another layout for mobile support

}

我看到这段代码,但我需要完整的代码,因为我在编码方面并不完美:(

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
switch(metrics.densityDpi){
  case DisplayMetrics.DENSITY_LOW:
            break;
  case DisplayMetrics.DENSITY_MEDIUM:
             break;
  case DisplayMetrics.DENSITY_HIGH:
             break;
}

2 个答案:

答案 0 :(得分:11)

根据official documentation,您无需以编程方式决定使用相应屏幕尺寸的布局。

  

针对不同的屏幕尺寸和优化应用程序的用户界面   密度,你可以为任何一个提供替代资源   广义的尺寸和密度。通常,您应该提供   一些不同屏幕尺寸的替代布局   用于不同屏幕密度的替代位图图像。 在运行时   系统会根据您的应用使用适当的资源   关于当前设备屏幕的广义大小或密度。

换句话说,如果您遵循文档中所述的建议,我可以看到您已完成,将布局文件放在各自的资源文件夹中,如下所示:

res/layout/main_activity.xml # For handsets (smaller than 600dp available width)
res/layout-sw600dp/main_activity.xml # For 7” tablets (600dp wide and bigger) 
res/layout-sw720dp/main_activity.xml # For 10” tablets (720dp wide and bigger)

然后系统将决定使用哪种布局。您无需在运行时指定其他代码。

如果您希望根据屏幕分辨率进行更改,则可以使用以下代码获取宽度和高度(以像素为单位)

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;

然后根据widthheight变量做一些切割工具,例如在你的情况下与S2:

if(width == 480 && height == 800){
    //Do work that's related to the S2 screen resolution
}else if(...){

}

答案 1 :(得分:1)

如果你问如何获得设备屏幕的密度,我花了3秒钟才找到答案(不包括键入时间" android获取设备密度&#34 ;进入我最喜欢的搜索引擎):

getting the screen density programmatically in android?