Android Fragment完全解析,关于碎片你所需知道的一切

一. 什么是Fragment
Fragment(碎片)就是小型的Activity,它是在Android3.0时出现的。Fragment是表现Activity中UI的一个行为或者一部分。
可以把fragment想象成activity的一个模块化区域,有它自己的生命周期,接收属于它自己的输入事件,并且可以在activity运行期间添加和删除(有点像一个可以在不同的activity中重用的“子Activity”)。
Fragment必须被嵌入到一个activity中。它们的生命周期直接受其宿主activity的生命周期影响。当一个activity正在运行时,就可以独立地操作每一个Fragment,比如添加或删除它们。
Fragment可以定义自己的布局、生命周期回调方法,因此可以将fragment重用到多个activity中,因此可以根据不同的屏幕尺寸或者使用场合改变fragment组合。

二. 如何创建一个Fragment
1、为Fragment定义一个布局
2、定义类继承Fragment
3、重写类中的onCreateView方法,返回一个View对象作为当前Fragment的布局。
fragment第一次绘制它的用户界面的时候,系统会调用onCreateView()方法。为了绘制fragment的UI,此方法必须返回一个作为fragment布局的根的view。如果fragment不提供UI,可以返回null。

代码:如Fragment01和Fragment02所示。

三. 如何将Fragment添加到Activity
Activity必须在清单文件中进行声明,但是Fragment不需要,Fragment只需要在Activity的布局文件layout_main.xml中声明就可以了。

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false" > <fragment
android:id="@+id/fragment1"
android:name="com.example.fragmentdemo.Fragment01"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="1" /> <fragment
android:id="@+id/fragment2"
android:name="com.example.fragmentdemo.Fragment02"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="1" /> </LinearLayout>

Fragment的代码:

 package com.example.fragmentdemo;

 import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup; /**
* Created by gary on 2016/4/12.
*/
public class Fragment01 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//return super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.fragment1,container,false);
}
} package com.example.fragmentdemo; import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup; /**
* Created by gary on 2016/4/12.
*/
public class Fragment02 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//return super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.fragment1,container,false);
}
}

Fragment的布局文件

 fragment1.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:background="#00ff00"> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="第一个Fragment"
android:textColor="#ff0000"
android:textSize="25sp"/> </LinearLayout> ------------------------
fragment2.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:background="#ff0000"> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="第二个Fragment"
android:textColor="#00ff00"
android:textSize="25sp"/> </LinearLayout>

Activity代码:

 package com.example.fragmentdemo;

 import android.app.Activity;
import android.os.Bundle; /**
* Created by gary on 2016/4/12.
*/
public class MainActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
}
}

效果:

http://i.cnblogs.com/EditPosts.aspx?postid=5380639

注意:代码中的四个属性是必须的要给的,“android:name”属性:指定了在layout中实例化的Fragment类是哪个。

当系统创建这个activitylayout时,它实例化每一个在layout中指定的Fragment,并调用它们的onCreateView()方法,来获取每一个Fragment的layout,系统将从Fragment返回的View直接插入到<fragment>元素所在的地方。

四. 如何动态何切换Fragment

要在Activity中管理Fragment,需要四步

1. 获取FragmentManger对象,在Activity可以通过getFragementManager()来获取实例。

  //1.获取Fragment管理器对象
FragmentManager manager = getFragmentManager();

2.开启一个事务,通过调用beginTransaction方法开启。

  //2. 开启事务
FragmentTransaction transaction = manager.beginTransaction();

3.向容器中加入Fragment,一般使用replace方法实现,需要传入容器的id和Fragment的实例。

  //3. 将FrameLayout控件替换成Fragment对象
transaction.replace(R.id.frame, new GamesFragment());

4. 提交事务,调用commit方法提交。

 //4. 提交事务
transaction.commit();

案例:点击不同的按钮切换到不同的Fragment进行显示。

具体实现步骤:

1. 设置布局文件layout_main.xml中添加三个按钮用于切换Fragment,并在按钮下方添加一个FrameLayout用来替换成相应的Fragment布局。

 <?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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="新闻"
android:onClick="news"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="体育"
android:onClick="sports"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="游戏"
android:onClick="games"/> </LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/frame"/> </LinearLayout>

2. 创建Fragment的布局文件,fragment_news.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"> <TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="新闻栏目"
android:textSize="28sp"
android:textColor="#0000ff"/>
</LinearLayout>

fragment_sports.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">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="体育栏目"
android:textSize="28sp"
android:textColor="#ff0000"/>
</LinearLayout>

fragment_games.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">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="游戏栏目"
android:textSize="28sp"
android:textColor="#00ff00"/>
</LinearLayout>

3. 创建三个Fragment,SportsFragment、NewsFragment、GameFragment。

 public class NewsFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// return super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.fragment_news,null);
}
}

SportFragment和GamesFragment中代码和NewsFragment相似。

4. 添加切换Fragment的逻辑,分别添加新闻、体育、游戏的点击事件。

 public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
} public void news(View v){
//获取Fragment管理器对象
FragmentManager manager = getFragmentManager();
//开启事务
FragmentTransaction transaction = manager.beginTransaction();
//将FrameLayout控件替换成Fragment对象
transaction.replace(R.id.frame, new NewsFragment());
//提交事务
transaction.commit();
}
public void games(View v){
//获取Fragment管理器对象
FragmentManager manager = getFragmentManager();
//开启事务
FragmentTransaction transaction = manager.beginTransaction();
//将FrameLayout控件替换成Fragment对象
transaction.replace(R.id.frame, new GamesFragment());
//提交事务
transaction.commit();
}
public void sports(View v){
//获取Fragment管理器对象
FragmentManager manager = getFragmentManager();
//开启事务
FragmentTransaction transaction = manager.beginTransaction();
//将FrameLayout控件替换成Fragment对象
transaction.replace(R.id.frame, new SportsFragment());
//提交事务
transaction.commit();
}
}

sports()方法、games()方法同上

5. 运行效果

Android之Fragment学习笔记①的更多相关文章

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

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

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

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

  3. Android安装器学习笔记(一)

    Android安装器学习笔记(一) 一.Android应用的四种安装方式: 1.通过系统应用PackageInstaller.apk进行安装,安装过程中会让用户确认 2.系统程序安装:在开机的时候自动 ...

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

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

  5. android cocos2d-x for Android安装和学习笔记(请用adt-bundle21.1或以上导入)

    引用:http://weimingtom.iteye.com/blog/1483566 (20121108)注意:这篇文章用cdt编译ndk工程的内容已过时(现在可以用adt-bundle,避免配置繁 ...

  6. 33.Android之Fragment学习

    Fragment Android是在Android 3.0 (API level 11)开始引入Fragment的. 可以把Fragment想成Activity中的模块,这个模块有自己的布局,有自己的 ...

  7. Fragment 学习笔记(1)

    网上关于Fragment相关的博客资料很多,写关于这个知识笔记是加深记忆,大神略过: 0x01 了解Fragment 当然看官方文档(http://www.android-doc.com/refere ...

  8. Fragment学习笔记

    Fragment为大量型号,尺寸,分辨率的设备提供了一种统一的UI优化方案.将Activity分解为多个Fragment,将极大地提高UI的灵活性,也更容易为一些新的设备配置带来更好的用户体验. on ...

  9. Android Fragment学习笔记(二)----Fragment界面添加和管理

    Fragment界面添加 了解过fragment的生命周期等简单知识,于是去看官方文档来了解更多相关内容,要添加fragment到我们的UI界面中,给出了两种常用的方法,第一个是在activity的布 ...

随机推荐

  1. CPU的性能对比

    笔记本CPU之前的性能对比 下面的分数都是根据PerformanceTest测试的出来的结果,现在的笔记本CPU有很多种,你在购买笔记本的时候只看到CPU的型号,而且现在的CPU型号太多而且命名方式也 ...

  2. struts2文件下载,动态设置资源地址

    转自:http://blog.csdn.net/ctrl_shift_del/article/details/6277340 ServletActionContext.getServletContex ...

  3. Gym 100971D Laying Cables 单调栈

    Description One-dimensional country has n cities, the i-th of which is located at the point xi and h ...

  4. Burpsuite教程与技巧之HTTP brute暴力破解

    Burpsuite教程与技巧之HTTP brute暴力破解 Gall @ WEB安全 2013-02-28 共 19052 人围观,发现 32 个不明物体收藏该文 感谢Gall投递 常规的对usern ...

  5. Myeclipse 60.激活

    Myeclipse 用来开发java web应用是十分的方便的,不过如果没有激活的话,用起来感觉会非常不爽. 当然,个人来说还是非常支持正版的,也鼓励大家支持正版. 好了,下面介绍一下怎么破解Myec ...

  6. haohantechsoft-PDA软件,PDA管理软件,PDA管理系统,仓库PDA销售开单盘点软件

    为了更好服务于广大服装客户群体进行销售.盘点.调拨配送等.推出基于无线网络版移动PDA销售开单盘点软件系统.该系统支持无线3G.WIFI.GPRS系统,用户可以手持PDA在无线网络连接状态下进行销售. ...

  7. 素数环问题[XDU1010]

    Problem 1010 - 素数环问题 Time Limit: 1000MS   Memory Limit: 65536KB   Difficulty: Total Submit: 972  Acc ...

  8. cocos2d 单点触控

    // // Single.hpp // dev // // Created by sun on 15/12/20. // // #ifndef Single_hpp #define Single_hp ...

  9. 给iOS工程增加Daily Build

    给iOS工程增加Daily Build  前言 Daily Build 是一件非常有意义的事情,也是敏捷开发中关于 "持续集成" 的一个实践.Daily Build 对于开发来说有 ...

  10. iOS开发中代理使用出现的问题解决

    在给自定义的LHQTabBar设置代理的时候,定义的代理的属性的时候此时会报一个警告 我们需要遵守UITabBarDelegate的协议才行, 不过此时还有警告,警告已经变成了 此时我们需要在.m文件 ...