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学习的更多相关文章

  1. Android之Fragment学习笔记①

    Android Fragment完全解析,关于碎片你所需知道的一切 一. 什么是FragmentFragment(碎片)就是小型的Activity,它是在Android3.0时出现的.Fragment ...

  2. Android之Fragment学习总结(1)

    对于Fragment的学习: 近日初步学习了Fragment这以特殊的组件,其依托与一个Activity,与Activity的生命周期息息相关,为其设置的视图只有当其关联到一个Activity才会起效 ...

  3. [android]p7-1 fragment学习笔记

    本文源自<android权威编程指南第3版>第7章UI fragment与fragment 第7章主要内容是实现一个记录不良行为的APP(部分实现),有列表,有具体的行为内容显示.第7章主 ...

  4. Android之Fragment学习笔记②(Fragment生命周期)

    一. Fragment生命周期图                                  二.Fragment生命周期方法介绍 Fragment的生命周期和activity生命周期很像,其生 ...

  5. Android应用开发学习笔记之Fragment

    作者:刘昊昱 博客:http://blog.csdn.net/liuhaoyutz Fragment翻译成中文就是“碎片”.“片断”的意思,Fragment通常用来作为一个Activity用户界面的一 ...

  6. [转]Android 使用Fragment界面向下跳转并一级级返回

      1.首先贴上项目结构图: 2.先添加一个接口文件BackHandledInterface.java,定义一个setSelectedFragment方法用于设置当前加载的Fragment在栈顶,主界 ...

  7. Android使用Fragment实现TabHost效果

    现在Fragment的应用真的是越来越广泛了,之前Android在3.0版本加入Fragment的时候,主要是为了解决Android Pad屏幕比较大,空间不能充分利用的问题,但现在即使只是在手机上, ...

  8. Android之SurfaceView学习(一)转转

    Android之SurfaceView学习(一) 首先我们先来看下官方API对SurfaceView的介绍 SurfaceView的API介绍 Provides a dedicated drawing ...

  9. 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 ...

随机推荐

  1. 使用 ssh 连接github的方法说明(gitub的官方说法)

    https://help.github.com/articles/generating-an-ssh-key/

  2. View (五)自定义View的实现方法

    一些接触Android不久的朋友对自定义View都有一丝畏惧感,总感觉这是一个比较高级的技术,但其实自定义View并不复杂,有时候只需要简单几行代码就可以完成了. 如果说要按类型来划分的话,自定义Vi ...

  3. 【转】【Asp.Net】asp.net(c#) 网页跳转

    在asp.net下,经常需要页面的跳转,下面是具体的几种方法.跳转页面是大部编辑语言中都会有的,正面我们来分别介绍一下关于.net中response.redirect sever.execute se ...

  4. 检查c# 内存泄漏

    c# 内存泄漏检查心得 系统环境 windows 7 x64 检查工具:ANTS Memory Profiler 7 或者 .NET Memory Profiler 4.0 开发的软件为winform ...

  5. PPPOE原理及部署

    PPPOE 1,一个广播域 2,panabit可以做小区项目 http://edu.51cto.com/course/course_id-3849.html   Adsl的介绍 所谓非对称,即上下行速 ...

  6. C# lambda表达式及初始化器

    using System;using System.Collections.Generic; using System.Linq; namespace ConsoleApplication1d { c ...

  7. OSGEARTH三维地形开源项目

    第一章   OSGEarth介绍 第二章   OSGEarth编译环境配置 OSGEarth的编译环境配置随着版本的不同.运行平台的不同,也有很大的差异.本章主要以Windows XP SP3(x86 ...

  8. LeetCode 笔记24 Palindrome Partitioning II (智商碾压)

    Given a string s, partition s such that every substring of the partition is a palindrome. Return the ...

  9. 第一周Web类WriteUp

    Forms 看到这题目第一反应就是先抓个包试试,抓包之后效果如图所示 看到一个showsource=0,那就想着把它改成1看看会出现什么效果,改成1之后forward,发现网页上变成了这个样子 根据这 ...

  10. java8新特性全面解析

    在Java Code Geeks上有大量的关于Java 8 的教程了,像玩转Java 8--lambda与并发,Java 8 Date Time API 教程: LocalDateTime和在Java ...