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以便设置按钮监听事件。 

点击打开链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值