(每次学习一点xamarin就做个学习笔记视频来加深记忆巩固知识)
如有不正确的地方,请帮我指正。
Fragment简介
Android程序运行在手机、平板和电视等各种设备中,各设备屏幕尺寸差距很大。不希望做几套程序来适应不同尺寸的设备。Fragment的产生就是解决这种问题。
Fragment是一种可以嵌入在Activity中的UI片段。
Fragment是Android3.0开始引入的新API技术。在Fragment中嵌套Fragment的功能是在Android4.2系统中才开始支持的,如果要在4.2之前系统运行就要使用support-v4库。
Fragment的生命周期
下面是一张官网图:
可以看到和activity的生命周期类似,多了几个方法。
OnAttach()当片段和活动建立关联时调用。
OnCreateView()当片段加截布局时调用。
OnActivityCreated()当与片段相关联的活动创建完毕后调用。
OnDestroyView()当与片段关联的视图被移除的时候调用。
OnDetach()当片段和活动解除关联的时候调用。
实现一个下面的图功能,左边是图书列表,右边是图书介绍。这个界面是针对平板电脑的。而在手机界面中只显示左边的这块,通过点击左边书名再在另一个新界面显示书的简介。
下面是一张项目文件部分截图:
可以看到有两个Main布局文件,一个是在默认layout目录中,一个在layout-sw600dp中,当程序运行在大于宽度600dp屏幕上时,系统会自动使用layout-sw600dp的Main布局, 宽度小于600dp则使用layout目录中的Main布局。(sw是Smallest-width的缩写)
默认的layout目录中的Main布局文件代码如下:
<?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/bookRecyclerFragment"
android:name="A07.BookRecyclerFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
就只有一个fragment,即书名列表片段bookRecyclerFragment。
Layout-sw600目录中的Main布局文件代码如下:
<?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/bookRecyclerFragment"
android:name="A07.BookRecyclerFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"/>
<FrameLayout
android:id="@+id/bookDescriptionFrameLayout"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3">
<fragment
android:id="@+id/bookDescriptionFragment"
android:name="A07.BookDescriptionFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
</LinearLayout>
这个布局文件用于宽度大于600dp的设备上,所以可显示两个片段,左边的书名列表片段bookRecyclerFragment和右边的书简介片段bookDescriptionFragment。
完整代码和视频在我上传的优快云资源中http://download.youkuaiyun.com/detail/junshangshui/9910017
本文介绍了Fragment的概念及其在Android开发中的作用,特别是在不同屏幕尺寸设备上的应用。Fragment是一种UI片段,可嵌入到Activity中,有助于统一管理不同尺寸屏幕的界面布局。
983

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



