xamarin学习笔记A07(安卓Fragment)

来源:互联网 发布:淘宝的淘宝客在哪里 编辑:程序博客网 时间:2024/06/05 21:15

(每次学习一点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。

完整代码和视频在我上传的CSDN资源中http://download.csdn.net/detail/junshangshui/9910017

原创粉丝点击