Android在3.0版本加入了Fragment,主要是为了解决Android Pad屏幕比较大,空间不能充分利用的问题,但现在即使只是在手机上,也有很多的场景可以。然而现在Fragment的应用的场景越来越多,Fragment意为碎片的意思,就是为了替代TabActivity。 例如,微信下方的tab:
可以将Fragment理解为Activity的“碎片”,也就是其一部分,故而Fragment的生命周期必定受Activity的影响。Fragment往往嵌入到Activity中,然后执行Fragment事务进行对Fragment的操作。
Fragment事务其实是维护了一个栈,这个栈存放了Fragment的每个事务,正因为有Fragment事务这种良好设计,我们可以将多个操作放在一起执行,再进行提交(commit),这样Fragment很好支持了“返回”的操作。
下面为Fragment的生命周期(与Activity生命周期放在一起,图摘自eoe):
下面将进行微信底部tab的样式模仿。起初的思路是利用FragmentTabHost,Android既然存在这样的封装就有价值,他为我们省下了很多代码,很多事情不用考虑,也降低了bug的产生。但FragmentTabHost 有局限性,每次切换Fragment时,都会调用onCreateView,这样就不能保存上次的状态,虽然可以通过缓存上次的Fragment解决,但不是根本方法,且代码设计角度来看也不够优雅。这里不使用FragmentTabHost ,通过自己的方法实现Fragment的Tab效果,较之FragmentTabHost ,可扩展性更好。
实现的效果图如下:
主布局代码:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<FrameLayout
android:id="@+id/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/bottomArea"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:background="#FFFFFF" >
</FrameLayout>
<RelativeLayout
android:id="@+id/bottomArea"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
>
<!-- tab的分割线 -->
<ImageView
android:id="@+id/tabTop"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#B6B6B6" />
<!-- tab的四个按钮 -->
<LinearLayout
android:id="@+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/tabTop"
android:layout_marginTop="1dp"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<!-- 微信按钮 -->
<!-- 使用FrameLayout,最主要的原因是使用它可以很容易的再添加一个消息提醒的小图片 -->
<FrameLayout
android:id="@+id/weixinLayout"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_weight="1"
android:paddingTop="3dp"
android:paddingBottom="2dp">
<ImageView
android:id="@+id/weixinImageView"
android:layout_width="96px"
android:layout_height="84px"
android:layout_gravity="top|center"
android:src="@drawable/weixin" />
<TextView

本文介绍了如何在Android应用中使用Fragment来模仿微信底部菜单栏的功能。探讨了Fragment的生命周期和事务管理,指出FragmentTabHost的局限性,并提供了自定义实现方式以提高可扩展性。示例代码包括主布局、Fragment布局、主Activity和具体Fragment的实现。

5420

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



