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. adb 卸载APP命令和杀死APP命令

    使用adb 卸载APP命令 在cmd命令行下,直接 输入 adb uninstall 包名 比如 adb uninstall com.ghstudio.BootStartDemo 杀死APP命令 先用 ...

  2. HDU 4349 Xiao Ming's Hope lucas定理

    Xiao Ming's Hope Time Limit:1000MS     Memory Limit:32768KB  Description Xiao Ming likes counting nu ...

  3. Adapter适配器

    1.概念 *连接后端数据和前端显示的适配器接口 *数据和UI之间的重要连接   2. ArrayAdapter  ArrayAdapter构造器如下: ArrayAdapter(Context con ...

  4. ember.js:使用笔记4 数组数据的分组显示

    除了之前介绍的将数组数据在一个页面中输出的方法,还可以将数组数据分组,按照点击,在不同页面中分别显示,方法为: Model: 例如:Table Router: 设置一个父对象和子对象设置: this. ...

  5. XMLHTTPRequest对象

    1.用于在后台与服务器交换数据: 2.XMLHttpRequest对象可以在不向服务器提交整个页面的情况下,实现局部更新网页.当页面全部加载完毕后,客户端通过该对象向服务器请求数据, 服务器端接受数据 ...

  6. StringUtils中 isNotEmpty 和isNotBlank的区别【java字符串判空】

    isNotEmpty(str)等价于 str != null && str.length > 0 isNotBlank(str) 等价于 str != null &&am ...

  7. 简单几何(凸包+多边形面积) POJ 3348 Cows

    题目传送门 题意:求凸包 + (int)求面积 / 50 /************************************************ * Author :Running_Tim ...

  8. HDU4276 The Ghost Blows Light(树形DP+背包)

    题目大概说一棵n个结点树,每个结点都有宝藏,走过每条边要花一定的时间,现在要在t时间内从结点1出发走到结点n,问能获得最多的宝藏是多少. 放了几天的题,今天拿出来集中精力去想,还是想出来了. 首先,树 ...

  9. KMP算法(转载)

    转载http://blog.csdn.net/yutianzuijin/article/details/11954939 kmp算法又称“看毛片”算法,是一个效率非常高的字符串匹配算法.不过由于其难以 ...

  10. 编程中i++与++i的区别