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

ame*_*lem 6 layout android 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"

摩托罗拉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
Run Code Online (Sandbox Code Playgroud)

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

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


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

if (tabletDeviceSize) {

//use tablet support layout

} else

{

//another layout for mobile support

}
Run Code Online (Sandbox Code Playgroud)

我看到这个代码,但我需要完整的代码,因为我不是完美的编码:(

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;
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*cus 11

根据官方文档,您无需以编程方式决定使用相应屏幕大小的布局.

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

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

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)
Run Code Online (Sandbox Code Playgroud)

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

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

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
Run Code Online (Sandbox Code Playgroud)

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

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

}
Run Code Online (Sandbox Code Playgroud)