33.Android之Fragment学习
Fragment
Android是在Android 3.0 (API level 11)开始引入Fragment的。
可以把Fragment想成Activity中的模块,这个模块有自己的布局,有自己的生命周期,单独处理自己的输入,在Activity运行的时候可以加载或者移除Fragment模块。
可以把Fragment设计成可以在多个Activity中复用的模块。
当开发的应用程序同时适用于平板电脑和手机时,可以利用Fragment实现灵活的布局,改善用户体验。
如图:

Fragment的生命周期
因为Fragment必须嵌入在Acitivity中使用,所以Fragment的生命周期和它所在的Activity是密切相关的。
如果Activity是暂停状态,其中所有的Fragment都是暂停状态;如果Activity是stopped状态,这个Activity中所有的Fragment都不能被启动;如果Activity被销毁,那么它其中的所有Fragment都会被销毁。
但是,当Activity在活动状态,可以独立控制Fragment的状态,比如加上或者移除Fragment。
当这样进行fragment transaction(转换)的时候,可以把fragment放入Activity的back stack中,这样用户就可以进行返回操作。

Fragment的使用相关
使用Fragment时,需要继承Fragment或者Fragment的子类(DialogFragment, ListFragment, PreferenceFragment, WebViewFragment),所以Fragment的代码看起来和Activity的类似。
今天我就模仿微信界面写个fragment例子,来小结下fragment学习。
首先添加四个要添加的fragment类,如图:

weixinframent.java代码:
package com.example.fragmentdemo; import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup; public class weixinframent extends Fragment
{ public static final String FRAGMENT_TAG = weixinframent.class.getName();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
return inflater.inflate(R.layout.layout1, container, false);
} }
telfragment.java代码:
package com.example.fragmentdemo; import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup; public class telfragment extends Fragment
{ public static final String FRAGMENT_TAG = telfragment.class.getName();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
return inflater.inflate(R.layout.layout2, container, false);
} }
findfragment.java代码:
package com.example.fragmentdemo; import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup; public class findfragment extends Fragment
{ public static final String FRAGMENT_TAG = findfragment.class.getName();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
return inflater.inflate(R.layout.layout3, container, false);
} }
mefragment.java代码:
package com.example.fragmentdemo; import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup; public class mefragment extends Fragment
{
public static final String FRAGMENT_TAG = mefragment.class.getName();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
return inflater.inflate(R.layout.layout4, container, false);
} }
然后增加四个fragment对应的布局文件,如图:

layout1.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"
android:orientation="vertical"> <TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="这是一个微信 fragment" /> </LinearLayout>
layout2.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"
android:orientation="vertical" > <TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="这是一个通信录 fragment" /> </LinearLayout>
layout3.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"
android:orientation="vertical" > <TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="这是一个发现 fragment" /> </LinearLayout>
layout4.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"
android:orientation="vertical" > <TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="这是一个我 fragment" /> </LinearLayout>
接着修改主布局文件:
<?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"
android:orientation="vertical"
android:id="@+id/main_root"> <RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"> <RelativeLayout
android:id="@+id/bottom_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"> <View
android:id="@+id/top_line"
android:layout_width="fill_parent"
android:layout_height="0.5dp"
android:layout_alignParentTop="true"
android:background="#19000000"/> <LinearLayout
android:layout_width="fill_parent"
android:layout_height="48dp"
android:layout_below="@id/top_line"
android:background="#D3FFFFFF"
android:orientation="horizontal"> <LinearLayout
android:id="@+id/tab1_layout"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical"> <ImageView
android:id="@+id/imageView1"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="4dp"
android:background="@drawable/tab1"/> <TextView
android:id="@+id/tab1_textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:gravity="center_horizontal"
android:text="微信"
android:textSize="10sp"/>
</LinearLayout> <LinearLayout
android:id="@+id/tab2_layout"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical"
android:gravity="center"> <RelativeLayout
android:layout_width="40dp"
android:layout_height="wrap_content"> <LinearLayout
android:layout_width="30dp"
android:orientation="vertical"
android:layout_height="fill_parent"
android:layout_centerInParent="true"> <ImageView
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="4dp"
android:background="@drawable/tab2"/> <TextView
android:id="@+id/tab2_textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:gravity="center_horizontal"
android:text="通信录" android:textSize="10sp"/>
</LinearLayout> <View
android:id="@+id/flag_red_dot"
android:layout_width="8dp"
android:layout_height="8dp"
android:layout_marginTop="4dp"
android:layout_alignParentRight="true"
android:visibility="gone"
/> </RelativeLayout>
</LinearLayout> <LinearLayout
android:id="@+id/tab3_layout"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical"> <ImageView
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="4dp"
android:background="@drawable/tab3"/> <TextView
android:id="@+id/tab3_textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:gravity="center_horizontal"
android:text="发现" android:textSize="10sp"/>
</LinearLayout> <LinearLayout
android:id="@+id/tab4_layout"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical"> <ImageView
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="4dp"
android:background="@drawable/tab4"/> <TextView
android:id="@+id/tab4_textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:gravity="center_horizontal"
android:text="我" android:textSize="10sp"/>
</LinearLayout>
</LinearLayout>
</RelativeLayout> <FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/bottom_layout">
</FrameLayout> </RelativeLayout> </LinearLayout>
最后修改MainActivity文件:
package com.example.fragmentdemo; import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout; public class MainActivity extends Activity implements OnClickListener { private LinearLayout m_weixintab;
private LinearLayout m_teltab;
private LinearLayout m_findtab;
private LinearLayout m_metab;
private LinearLayout m_curtab; private weixinframent mweixin = null;
private telfragment mtel = null;
private findfragment mfind = null;
private mefragment mMe = null;
private Fragment mCurrentfragment = null; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); m_weixintab = (LinearLayout) findViewById(R.id.tab1_layout);
m_teltab = (LinearLayout) findViewById(R.id.tab2_layout);
m_findtab = (LinearLayout) findViewById(R.id.tab3_layout);
m_metab = (LinearLayout) findViewById(R.id.tab4_layout); m_weixintab.setOnClickListener(this);
m_teltab.setOnClickListener(this);
m_findtab.setOnClickListener(this);
m_metab.setOnClickListener(this); m_weixintab.setSelected(true);
m_weixintab.setVisibility(View.VISIBLE); if (null == savedInstanceState) {
mCurrentfragment = getweixinFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.content_frame, mCurrentfragment,
weixinframent.FRAGMENT_TAG);
ft.commit();
} else {
mCurrentfragment = getweixinFragment();
} m_curtab = m_weixintab; } private weixinframent getweixinFragment() {
weixinframent fragment = (weixinframent) getFragmentManager()
.findFragmentByTag(weixinframent.FRAGMENT_TAG);
if (null == fragment) {
fragment = new weixinframent();
}
return fragment;
} private telfragment gettelFragment() {
telfragment fragment = (telfragment) getFragmentManager()
.findFragmentByTag(telfragment.FRAGMENT_TAG);
if (null == fragment) {
fragment = new telfragment();
}
return fragment;
} private findfragment getfindFragment() {
findfragment fragment = (findfragment) getFragmentManager()
.findFragmentByTag(findfragment.FRAGMENT_TAG);
if (null == fragment) {
fragment = new findfragment();
}
return fragment;
} private mefragment getmeFragment() {
mefragment fragment = (mefragment) getFragmentManager()
.findFragmentByTag(mefragment.FRAGMENT_TAG);
if (null == fragment) {
fragment = new mefragment();
}
return fragment;
} @Override
public void onClick(View v) { FragmentTransaction ft = getFragmentManager().beginTransaction();
String tag = null;
Fragment changefragment = null;
switch (v.getId()) {
case R.id.tab1_layout:
if (mweixin == null) {
m_curtab.setSelected(false);
m_weixintab.setSelected(true);
m_curtab = m_weixintab;
changefragment = this.getweixinFragment();
tag = weixinframent.FRAGMENT_TAG;
}
break; case R.id.tab2_layout:
if (mtel == null) {
m_curtab.setSelected(false);
m_teltab.setSelected(true);
m_curtab = m_teltab;
changefragment = this.gettelFragment();
tag = telfragment.FRAGMENT_TAG;
}
break; case R.id.tab3_layout:
if (mfind == null) {
m_curtab.setSelected(false);
m_findtab.setSelected(true);
m_curtab = m_findtab;
changefragment = this.getfindFragment();
tag = findfragment.FRAGMENT_TAG;
}
break; case R.id.tab4_layout:
if (mMe == null) {
m_curtab.setSelected(false);
m_metab.setSelected(true);
m_curtab = m_metab;
changefragment = this.getmeFragment();
tag = mefragment.FRAGMENT_TAG;
}
break;
} if (changefragment != null) {
Fragment f = getFragmentManager().findFragmentByTag(tag);
ft.hide(mCurrentfragment);
if (null == f) {
ft.add(R.id.content_frame, changefragment, tag);
} else {
ft.show(changefragment);
}
ft.commit();
mCurrentfragment = changefragment;
} } }
说明:使用Fragment时,可以通过用户交互来执行一些动作,比如增加、移除、替换等。所有这些改变构成一个集合,这个集合被叫做一个transaction,可以调用FragmentTransaction中的方法来处理这个transaction,并且可以将transaction存进由activity管理的back stack中,这样用户就可以进行fragment变化的回退操作。
可以这样得到FragmentTransaction类的实例:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
每个transaction是一组同时执行的变化的集合。用add(), remove(), replace()方法,把所有需要的变化加进去,然后调用commit()方法,将这些变化应用。
运行效果:

点击发现,界面变为如下图:

33.Android之Fragment学习的更多相关文章
- Android之Fragment学习笔记①
Android Fragment完全解析,关于碎片你所需知道的一切 一. 什么是FragmentFragment(碎片)就是小型的Activity,它是在Android3.0时出现的.Fragment ...
- Android之Fragment学习总结(1)
对于Fragment的学习: 近日初步学习了Fragment这以特殊的组件,其依托与一个Activity,与Activity的生命周期息息相关,为其设置的视图只有当其关联到一个Activity才会起效 ...
- [android]p7-1 fragment学习笔记
本文源自<android权威编程指南第3版>第7章UI fragment与fragment 第7章主要内容是实现一个记录不良行为的APP(部分实现),有列表,有具体的行为内容显示.第7章主 ...
- Android之Fragment学习笔记②(Fragment生命周期)
一. Fragment生命周期图 二.Fragment生命周期方法介绍 Fragment的生命周期和activity生命周期很像,其生 ...
- Android应用开发学习笔记之Fragment
作者:刘昊昱 博客:http://blog.csdn.net/liuhaoyutz Fragment翻译成中文就是“碎片”.“片断”的意思,Fragment通常用来作为一个Activity用户界面的一 ...
- [转]Android 使用Fragment界面向下跳转并一级级返回
1.首先贴上项目结构图: 2.先添加一个接口文件BackHandledInterface.java,定义一个setSelectedFragment方法用于设置当前加载的Fragment在栈顶,主界 ...
- Android使用Fragment实现TabHost效果
现在Fragment的应用真的是越来越广泛了,之前Android在3.0版本加入Fragment的时候,主要是为了解决Android Pad屏幕比较大,空间不能充分利用的问题,但现在即使只是在手机上, ...
- Android之SurfaceView学习(一)转转
Android之SurfaceView学习(一) 首先我们先来看下官方API对SurfaceView的介绍 SurfaceView的API介绍 Provides a dedicated drawing ...
- Android cannot be cast to android.app.Fragment
10-21 17:33:45.171: E/AndroidRuntime(7644): java.lang.RuntimeException: Unable to start activity Com ...
随机推荐
- java 16-6 泛型
ArrayList存储字符串并遍历 我们按照正常的写法来写这个程序, 结果确出错了. 为什么呢? 因为我们开始存储的时候,存储了String和Integer两种类型的数据. 而在遍历的时候,我们把它们 ...
- 关于软件测试人员能力模型的建立(from知乎)
转自: http://www.zhihu.com/question/20254092 测试思维方面:1.测试基础理论(测试流程.测试的基础知识)2.测试用例设计方法论(黑盒.白盒)3.软件质量体系(建 ...
- 图解Js event对象offsetX, clientX, pageX, screenX, layerX, x区别
通过 3 张图和 1 张表格,轻松区别 JavaScript Event 对象中的offsetX, clientX, pageX, screenX, layerX, x等属性. 一.测试代码如下: & ...
- form表单和ajax表单提交(Html.BeginForm()、Ajax.BeginForm())的差别
有如下几种区别: 1. Ajax在提交.请求.接收时,都是异步进行的,网页不需要刷新: Form提交则是新建一个页面,哪怕是提交给自己本身的页面,也是需要刷新的: 2. A在提交时,是在后台新建一个请 ...
- slatsatck file模块2种写法及系统初始化
一 . lamp搭建 file2种写法 saltstack--一键yum lamp:---请注意重点: http://www.blogs8.cn/posts/WLjId80 知识点: 文件的2种写 ...
- 拿什么拯救你,我的代码--c#编码规范实战篇 (转)
http://www.cnblogs.com/lazio10000/p/5413439.html 此文为译文,原文地址请点击. 本文通过重构一个垃圾代码,阐述了如何写出优秀的代码.开发人员及代码审核人 ...
- EL表达式 (详解)
L表达式 1.EL简介 1)语法结构 ${expression} 2)[]与.运算符 EL 提供.和[]两种运算符来存取数据. 当要存取的属性名称中包含一些 ...
- web.xml配置文件
一.web.xml里面的标签 <display-name> <context-param> <listener> <filter> 和 <filt ...
- 使用MarkdonPad2学习心得
使用MarkdonPad2学习心得 心得体会 自从接触了娄老师的课程后,逐渐的适应了使用博客园.实验楼等网络学习资源学习课程,虽说和传统的授课方式有些不同,但毕竟我们就是与电脑与网络打交道,所以在学习 ...
- 零散知识记录-Jira的安装
Jira不支持openjdk,在linux下需要卸载后,装个jdk才行.