Android屏幕、多分辨率适配

Android机型的多样性使得我们做一款APP时不得不得考虑平板、手机适配以及多分辨率的适配的问题。
对于这个问题的关键是理解res/layout-sw600dpres/layout-sw720dp ,在此我做一个总结:
由于平板和手机尺寸以及分辨率的不同,我们需要分别为之设置加载不同layout,启动APP后手机会自动判断应该分配给哪个layout。 

600dp的含义是:代表这个设备的最短的那一边。以平板为例(分辨率是1280*768,密度是1),最短边长是768。但是,如果分辨率为1920*1080,得到的值为360,此时使用的layout为res/layout-sw320dp,获取设备的最短边的代码是: 

Configuration config = getResources().getConfiguration(); 
intsmallestScreenWidth = config.smallestScreenWidthDp; 

当然计算问题,我不在此赘述。 


Android平板和手机如何适配 ?

新建一个Android项目,MainActivity默认加载的layout路径为res/layout/activity_main.xml,这可以作为手机适配的界面;在res下新建layout-sw600dp文件夹,在此文件夹下新建activity_main.xml,作为平板识别的layout。为了有所区别,下面给出代码: 

res/layout/activity_main.xml 

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 
    <TextView
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="Hello World!">
    </TextView>
</RelativeLayout >

res/layout-sw600dp/activity_main.xml

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 
    <TextView
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="sw600">
     </TextView> 
</RelativeLayout>

当我们分别在手机和平板上运行时,系统会自动识别应该加载的layout。这里给出的例子比较简单,如果activity_main.xml的内容比较复杂时,我们应该在Activity中判断加载的到底是哪个layout以便设置按钮监听事件。 

点击打开链接

发布了35 篇原创文章 · 获赞 37 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_34519487/article/details/79504880