Fragment(碎片)
1、碎片是什么
碎片(Fragment)是一种可以嵌入在活动当中的UI片段,它能让程序更加合理和充分地利用大屏幕的空间,因而在平板上应用的非常广泛。虽然碎片对你来说应该是个全新的概念,但我相信你学习起来应该毫不费力,因为它和活动实在是太像了,同样都能包含布局,同样都有自己的生命周期。你甚至可以将碎片理解成一个迷你型的活动,虽然这个迷你型的活动有可能和普通的活动是一样大的。
那么究竟要如何使用碎片才能充分地利用平板屏幕的空间呢?想象我们正在开发一个新闻应用,其中一个界面使用ListView展示了一组新闻的标题,当点击了其中一个标题,就打开另一个界面显示新闻的详细内容。如果是在手机中设计,我们可以将新闻标题列表放在一个活动中,将新闻的详细内容放在另一个活动中,如下图
可是如果在平板上也这么设计,那么新闻标题列表将会被拉长至填充满整个平板的屏幕,而新闻的标题一般都不会太长,这样将会导致界面上有大量的空白区域,如下图所示。
因此,更好的设计方案是将新闻标题列表界面和新闻详细内容界面分别放在两个碎片中,然后在同一个活动里引入这两个碎片,这样就可以将屏幕空间充分地利用起来了,如下图所示。
2、Fragment碎片的使用
(例子有点长,耐心看下去)
①、首先我们来定义一下一个主Activity的xml文件,将此布局文件分为左右两部分,左边为导航栏,右边为信息栏
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/left_fragement"
android:layout_width="0dp"
android:layout_weight="1.5"
android:layout_height="match_parent"
android:background="#EBC781"/>
<FrameLayout
android:id="@+id/right_fragement"
android:layout_width="0dp"
android:layout_weight="3"
android:layout_height="match_parent"
android:background="#04AF90"/>
</LinearLayout>
效果大致是这样的,分为左边和右边两个部分,分别用来装左右两个碎片
②、接下来定义左边的布局文件 layout_menu.xml,这里定义的是ListView列表视图
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
③、再给这个列表视图定义一个名为layout_item.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">
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_height="100dp"/>
<TextView
android:id="@+id/name"
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#fff"
android:textSize="18sp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"/>
<