您的位置:首页 > 移动开发 > Android开发

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

2017-03-23 17:16 465 查看
如果程序能够根据设备的分辨率或者屏幕的大小在运行时来决定加载那个布局,那我们发挥的空间就更多了。因此本节我们就来探讨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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐