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

最低0.47元/天 解锁文章
186

被折叠的 条评论
为什么被折叠?



