Android 适配不同屏幕(手机,平板)

如果程序能够根据设备的分辨率或者屏幕的大小在运行时来决定加载那个布局,那我们发挥的空间就更多了。因此本节我们就来探讨Android中动态加载布局,限定符的使用:

  • layout-large

  • layout-sw600dp


layout-large

为了同时适配手机和平板。
我们在res/目录下创建,layout-large的package,然后我们可以创建一个与layout下相同的activity_main.xml文件,

但是里面的布局不同
代码如下;
layout/下

<?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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.aofei.no1codedemo.MainActivity">

    <Button
        android:id="@+id/mian_btn"
        android:onClick="onClick"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/backgroud"
        android:text="on Click" />
</RelativeLayout>

layout-large下

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context="com.aofei.no1codedemo.MainActivity">

    <fragment
        android:id="@+id/fragment_left"
        android:name="com.aofei.no1codedemo.fragment.LeftFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />

    <fragment
        android:id="@+id/fragment_right"
        android:name="com.aofei.no1codedemo.fragment.RightFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />

</LinearLayout>

然后分别在手机和平板上运行后的效果如图

手机上

平板

layout-sw600dp

最小宽度限定符(Smallest-width Qualifier),允许我们对屏幕的宽度指定一个最小值(以dp为单位),然后以这个最小值为临界点,屏幕大于这个值的设备我们加载一个布局,屏幕小于这个值的设备,我们加载另一个布局。

当程序运行在大于600dp的设备上时,会加载layout-sw600dp/activity_main.xml布局,当程序运行在屏幕宽度小于600d p的设备上时,则仍然加载默认的layout/activity_main.xml.
需要注意的一点是,最小宽度限定符是在android 3.2版本引入的额,由于这里我们最低可兼容的系统版本是4.0.所以可以放心使用它。
项目地址:https://github.com/Kenway090704/FragmentBestPractice

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值