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 ...
随机推荐
- java9-2形式参数
1.形式参数: 基本类型(太简单) 引用类型 类名:(匿名对象的时候其实我们已经讲过了)需要的是该类的对象 抽象类:需要的是该抽象的类子类对象 接口:需要的是该接口的实现类对象 A. 类名:(匿名对象 ...
- <<Effective Java>>之善用组合而不是继承
使用JAVA这门OO语言,第一要义就是,如果类不是专门设计来用于被继承的就尽量不要使用继承而应该使用组合 从上图2看,我们的类B复写了类A的add喝addALL方法,目的是每次调用的时候,我们就能统计 ...
- 获取元素在浏览器中的绝对位置(从jquery1.8中抠出来)
<style> html,body{margin:0;padding:0;} .d1{margin-left:40px;background:red;width:2000px;height ...
- 5050 [JL] 他爱上了鸭蛋
5050 [JL] 他爱上了鸭蛋 时间限制: 1 s 空间限制: 1000 KB 题目等级 : 白银 Silver 题解 题目描述 Description 小明爱上了零鸭蛋.他喜欢输 ...
- Linux常用的基本命令
man命令:查看帮助信息 格式:man 需要查看的命令 date命令:显示时间 格式:# date ...
- 20135202闫佳歆--week 8 课本第4章学习笔记
第四章 进程调度 一.多任务 多任务操作系统就是能同时并发的交互执行多个进程的操作系统. 多任务操作系统使多个进程处于堵塞或者睡眠状态,实际不被投入执行,这些任务尽管位于内存,但是并不处于可运行状态. ...
- 整理sqlserver 级联更新和删除 c#调用存储过程返回值
整理一下级联更新和删除 c#调用返回值 use master go IF exists(select 1 from sysdatabases where name='temp') BEGIN DROP ...
- 深入探索Java 8 Lambda表达式
2014年3月,Java 8发布,Lambda表达式作为一项重要的特性随之而来.或许现在你已经在使用Lambda表达式来书写简洁灵活的代码.比如,你可以使用Lambda表达式和新增的流相关的API,完 ...
- iOS 自定义控件开发(上)
工作需要,最近在进行iOS方面的图表工作.找了很多第三方库都无法实现效果,所以决定自己写一个控件. <iOS 自定义控件开发(上)> <iOS 自定义控件开发(中)> #0 目 ...
- ASP.NET服务器控件使用之MultiView和View
MultiView 控件是一组 View 控件的容器.使用它可定义一组 View 控件,其中每个 View 控件都包含子控件. 用 ActiveViewIndex 属性或SetActiveView 方 ...