Android冒险之旅-18-手机与平板适配的思路

1. 总体思路

  为主页面设计两个同名布局,分别为单页布局(手机),双页布局(平板)。单页布局存放在layout目录下,双页布局存放在layout-sw600dp目录下。运行时系统会根据具体设备选择合适的布局。在java代码中通过一个特殊的控件ID(比如双页有单页没有的)来判断当前显示的是单页模式还是双页模式。如果是双页模式,那么资源直接加载,如果是单页模式,那么某个点击操作触发之后跳转到另一页面。
  本文案例:郭霖大神第四章碎片的最佳实践,一个简易版新闻应用。

2. 主页面布局(单页)

layout/activity_news.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/news_title_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <fragment
        android:id="@+id/news_title_fragment"
        android:name="qiyuan.lin.helloandroid.news.NewsTitleFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

</FrameLayout>

2. 主页面布局(双页)

layout-sw600dp/activity_news.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <fragment
        android:id="@+id/news_title_fragment"
        android:name="qiyuan.lin.helloandroid.news.NewsTitleFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />

    <FrameLayout
        android:id="@+id/news_content_layout"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="3" >

        <fragment
            android:id="@+id/news_content_fragment"
            android:name="qiyuan.lin.helloandroid.news.NewsContentFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </FrameLayout>

</LinearLayout>

4. 主活动

public class NewsActivity extends BaseActivity {
   
   

    @Override
    protected void onCreate(Bundle savedInstanceState) {
   
   
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news);
        /*
        * 这里开始解析主布局,而主布局静态绑定了Fragment碎片
        * 所以虽然没有任何代码
        * 但是下一步会加载碎片
        * 根据选择的主布局加载对应碎片
        * 单页布局加载NewsTitleFragment碎片
        * 双页模式加载NewsTitleFragment碎片和NewsContentFragment碎片
        * */
    }
}

5. NewsTitleFragment布局

news_title_frag.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">
    <androidx.recyclerview.widget.RecyclerView
        
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值