Android中Fragment 真正的完全解析(上)

自从Fragment出现,曾经有段时间,感觉大家谈什么都能跟Fragment谈上关系,做什么都要问下Fragment能实现不~~~哈哈,是不是有点过~~~

本文力求为大家说明Fragment如何产生,什么是Fragment,Fragment生命周期,如何静态和动态的使用Fragment,Fragment回退栈,Fragment事务;以及Fragment的一些特殊用途,例如:没有布局的Fragment有何用处?Fragment如何与Activity交互?Fragment如何创建对话框?Fragment如何与ActionBar集成等等。

1、Fragment的产生与介绍

Android运行在各种各样的设备中,有小屏
幕的手机,超大屏的平板甚至电视。针对屏幕尺寸的差距,很多情况下,都是先针对手机开发一套App,然后拷贝一份,修改布局以适应平板神马超级大屏的。难道无法做到一个App可以同时适应手机和平板么,当然了,必须有啊。Fragment的出现就是为了解决这样的问题。你可以把Fragment当成Activity的一个界面的一个组成部分,甚至Activity的界面可以完全有不同的Fragment组成,更帅气的是Fragment拥有自己的生命周期和接收、处理用户的事件,这样就不必在Activity写一堆控件的事件处理的代码了。更为重要的是,你可以动态的添加、替换和移除某个Fragment。

2、Fragment的生命周期

Fragment必须是依存与Activity而存在的,因此Activity的生命周期会直接影响到Fragment的生命周期。官网这张图很好的说明了两者生命周期的关系:

可以看到Fragment比Activity多了几个额外的生命周期回调方法:

onAttach(Activity)

当Fragment与Activity发生关联时调用。

onCreateView(LayoutInflater, ViewGroup,Bundle)

创建该Fragment的视图

onActivityCreated(Bundle)

当Activity的onCreate方法返回时调用

onDestoryView()

与onCreateView想对应,当该Fragment的视图被移除时调用

onDetach()

与onAttach相对应,当Fragment与Activity关联被取消时调用

注意:除了onCreateView,其他的所有方法如果你重写了,必须调用父类对于该方法的实现,

3、静态的使用Fragment

嘿嘿,终于到使用的时刻了~~

这是使用Fragment最简单的一种方式,把Fragment当成普通的控件,直接写在Activity的布局文件中。步骤:

1、继承Fragment,重写onCreateView决定Fragemnt的布局

2、在Activity中声明此Fragment,就当和普通的View一样

下面展示一个例子(我使用2个Fragment作为Activity的布局,一个Fragment用于标题布局,一个Fragment用于内容布局):

TitleFragment的布局文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemasandroidcom/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="45dp"
  android:background="@drawable/title_bar" > 

  <ImageButton
    android:id="@+id/id_title_left_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_marginLeft="3dp"
    android:background="@drawable/showleft_selector" /> 

  <TextView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:text="我不是微信"
    android:textColor="#fff"
    android:textSize="20sp"
    android:textStyle="bold" /> 

</RelativeLayout>

TitleFragment

package comzhyzhy_fragments; 

import androidappFragment;
import androidosBundle;
import androidviewLayoutInflater;
import androidviewView;
import androidviewViewOnClickListener;
import androidviewViewGroup;
import androidwidgetImageButton;
import androidwidgetToast; 

public class TitleFragment extends Fragment
{ 

  private ImageButton mLeftMenu; 

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState)
  {
    View view = inflaterinflate(Rlayoutfragment_title, container, false);
    mLeftMenu = (ImageButton) viewfindViewById(Ridid_title_left_btn);
    mLeftMenusetOnClickListener(new OnClickListener()
    {
      @Override
      public void onClick(View v)
      {
        ToastmakeText(getActivity(),
            "i am an ImageButton in TitleFragment ! ",
            ToastLENGTH_SHORT)show();
      }
    });
    return view;
  }
}

同理还有ContentFragment的其布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemasandroidcom/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical" > 

  <TextView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:text="使用Fragment做主面板"
    android:textSize="20sp"
    android:textStyle="bold" /> 

</LinearLayout>
package com.zhy.zhy_fragments; 

import androidappFragment;
import androidosBundle;
import androidviewLayoutInflater;
import androidviewView;
import androidviewViewGroup; 

public class ContentFragment extends Fragment
{ 

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState)
  {
    return inflaterinflate(Rlayoutfragment_content, container, false);
  } 

}

MainActivity

package com.zhy.zhy_fragments; 

import androidappActivity;
import androidosBundle;
import androidviewWindow; 

public class MainActivity extends Activity
{ 

  @Override
  protected void onCreate(Bundle savedInstanceState)
  {
    superonCreate(savedInstanceState);
    requestWindowFeature(WindowFEATURE_NO_TITLE);
    setContentView(Rlayoutactivity_main);
  } 

}

Activity的布局文件:

<RelativeLayout xmlns:android="http://schemasandroidcom/apk/res/android"
  xmlns:tools="http://schemasandroidcom/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent" > 

  <fragment
    android:id="@+id/id_fragment_title"
    android:name="comzhyzhy_fragmentsTitleFragment"
    android:layout_width="fill_parent"
    android:layout_height="45dp" /> 

  <fragment
    android:layout_below="@id/id_fragment_title"
    android:id="@+id/id_fragment_content"
    android:name="comzhyzhy_fragmentsContentFragment"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" /> 

</RelativeLayout> 

是不是把Fragment当成普通的View一样声明在Activity的布局文件中,然后所有控件的事件处理等代码都由各自的Fragment去处理,瞬间觉得Activity好干净有木有~~代码的可读性、复用性以及可维护性是不是瞬间提升了~~~下面看下效果图:

4、动态的使用Fragment

上面已经演示了,最简单的使用Fragment的方式~下面介绍如何动态的添加、更新、以及删除Fragment

为了动态使用Fragment,我们修改一下Actvity的布局文件,中间使用一个FrameLayout,下面添加四个按钮~~~嘿嘿~~不是微信的按钮- -!

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemasandroidcom/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent" > 

  <fragment
    android:id="@+id/id_fragment_title"
    android:name="comzhyzhy_fragmentsTitleFragment"
    android:layout_width="fill_parent"
    android:layout_height="45dp" /> 

  <include
    android:id="@+id/id_ly_bottombar"
    android:layout_width="fill_parent"
    android:layout_height="55dp"
    android:layout_alignParentBottom="true"
    layout="@layout/bottombar" /> 

  <FrameLayout
    android:id="@+id/id_content"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_above="@id/id_ly_bottombar"
    android:layout_below="@id/id_fragment_title" /> 

</RelativeLayout>

底部四个按钮的布局就不贴了,到时看效果图就明白了~~

下面主Activity

package com.zhy.zhy_fragments; 

import androidappActivity;
import androidappFragmentManager;
import androidappFragmentTransaction;
import androidosBundle;
import androidviewView;
import androidviewViewOnClickListener;
import androidviewWindow;
import androidwidgetLinearLayout; 

public class MainActivity extends Activity implements OnClickListener
{
  private LinearLayout mTabWeixin;
  private LinearLayout mTabFriend; 

  private ContentFragment mWeixin;
  private FriendFragment mFriend; 

  @Override
  protected void onCreate(Bundle savedInstanceState)
  {
    superonCreate(savedInstanceState);
    requestWindowFeature(WindowFEATURE_NO_TITLE);
    setContentView(Rlayoutactivity_main); 

    // 初始化控件和声明事件
    mTabWeixin = (LinearLayout) findViewById(Ridtab_bottom_weixin);
    mTabFriend = (LinearLayout) findViewById(Ridtab_bottom_friend);
    mTabWeixinsetOnClickListener(this);
    mTabFriendsetOnClickListener(this); 

    // 设置默认的Fragment
    setDefaultFragment();
  } 

  private void setDefaultFragment()
  {
    FragmentManager fm = getFragmentManager();
    FragmentTransaction transaction = fmbeginTransaction();
    mWeixin = new ContentFragment();
    transactionreplace(Ridid_content, mWeixin);
    transactioncommit();
  } 

  @Override
  public void onClick(View v)
  {
    FragmentManager fm = getFragmentManager();
    // 开启Fragment事务
    FragmentTransaction transaction = fmbeginTransaction(); 

    switch (vgetId())
    {
    case Ridtab_bottom_weixin:
      if (mWeixin == null)
      {
        mWeixin = new ContentFragment();
      }
      // 使用当前Fragment的布局替代id_content的控件
      transactionreplace(Ridid_content, mWeixin);
      break;
    case Ridtab_bottom_friend:
      if (mFriend == null)
      {
        mFriend = new FriendFragment();
      }
      transactionreplace(Ridid_content, mFriend);
      break;
    }
    // transactionaddToBackStack();
    // 事务提交
    transactioncommit();
  } 

}

可以看到我们使用FragmentManager对Fragment进行了动态的加载,这里使用的是replace方法~~下一节我会详细介绍FragmentManager的常用API。

注:如果使用Android3.0以下的版本,需要引入v4的包,然后Activity继承FragmentActivity,然后通过getSupportFragmentManager获得FragmentManager。不过还是建议版Menifest文件的uses-sdk的minSdkVersion和targetSdkVersion都改为11以上,这样就不必引入v4包了。

代码中间还有两个Fragment的子类,ContentFragment上面已经见过,FriendFragment其实类似:

package com.zhy.zhy_fragments; 

import androidappFragment;
import androidosBundle;
import androidviewLayoutInflater;
import androidviewView;
import androidviewViewGroup; 

public class FriendFragment extends Fragment
{ 

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState)
  {
    return inflaterinflate(Rlayoutfragment_friend, container, false);
  } 

}

效果图:

可以看到很好的实现了效果,其实这个效果以前的博客中也出现过,Fragment+TabPageIndicator+ViewPager,有兴趣可以看看。ps:为了代码的简洁,就不添加按钮的点击变化什么的了,主要讲解功能了~~~

5、Fragment家族常用的API

Fragment常用的三个类:

  • android.app.Fragment 主要用于定义Fragment
  • android.app.FragmentManager 主要用于在Activity中操作Fragment
  • android.app.FragmentTransaction 保证一些列Fragment操作的原子性,熟悉事务这个词,一定能明白~

a、获取FragmentManage的方式:

getFragmentManager() // v4中,getSupportFragmentManager

b、主要的操作都是FragmentTransaction的方法

FragmentTransaction transaction = fm.benginTransatcion();//开启一个事务

transaction.add()

往Activity中添加一个Fragment

从Activity中移除一个Fragment,如果被移除的Fragment没有添加到回退栈(回退栈后面会详细说),这个Fragment实例将会被销毁。

transaction.replace()

使用另一个Fragment替换当前的,实际上就是remove()然后add()的合体~

transaction.hide()

隐藏当前的Fragment,仅仅是设为不可见,并不会销毁

transaction.show()

显示之前隐藏的Fragment

detach()

会将view从UI中移除,和remove()不同,此时fragment的状态依然由FragmentManager维护。

attach()

重建view视图,附加到UI上并显示。

transatcion.commit()//提交一个事务

注意:常用Fragment的哥们,可能会经常遇到这样Activity状态不一致:State loss这样的错误。主要是因为:commit方法一定要在Activity.onSaveInstance()之前调用。

上述,基本是操作Fragment的所有的方式了,在一个事务开启到提交可以进行多个的添加、移除、替换等操作。

值得注意的是:如果你喜欢使用Fragment,一定要清楚这些方法,哪个会销毁视图,哪个会销毁实例,哪个仅仅只是隐藏,这样才能更好的使用它们。

a、比如:我在FragmentA中的EditText填了一些数据,当切换到FragmentB时,如果希望会到A还能看到数据,则适合你的就是hide和show;也就是说,希望保留用户操作的面板,你可以使用hide和show,当然了不要使劲在那new实例,进行下非null判断。

b、再比如:我不希望保留用户操作,你可以使用remove(),然后add();或者使用replace()这个和remove,add是相同的效果。

c、remove和detach有一点细微的区别,在不考虑回退栈的情况下,remove会销毁整个Fragment实例,而detach则只是销毁其视图结构,实例并不会被销毁。那么二者怎么取舍使用呢?如果你的当前Activity一直存在,那么在不希望保留用户操作的时候,你可以优先使用detach。

上述已经介绍完成了Fragment常用的一些方法,相信看完,大家一定清楚了Fragment的产生理由,以及如何使用Fragment,再根据API的讲解,也能明白,曾经为何觉得Fragment会出现一些列乱七八槽的问题,终究是因为没有弄清楚其生命周期。

由于篇幅原因,剩下的内容留到下一篇了。在下一篇,会介绍:

1、如何管理Fragment回退栈

2、Fragment如何与Activity交互

3、Fragment与Activity交互的最佳实践

4、没有视图的Fragment的用处

5、使用Fragment创建对话框

6、如何与ActionBar,MenuItem集成等~~

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • Android App中使用ViewPager+Fragment实现滑动切换效果

    在android应用中,多屏滑动是一种很常见的风格,没有采用viewpager的代码实现会很长,如果采用ViewPager,代码就会短很多,但是使用ViewPager也有弊端:需要导入android-support-v4.jar.细节无法控制.不过现在情况已经不一样了,android-support-v4中提供了很多实用的功能,以至于现在新建一个android工程默认都会导入这个jar包.那我们就也采用viewpager来做滑动吧.另外一个概念就是Fragment和FragmentActivit

  • 详解Android应用中DialogFragment的基本用法

    DialogFragment的基本用法 1. 创建DialogFragment public class DialogA extends DialogFragment implements DialogInterface.OnClickListener { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder

  • Android的Fragment的生命周期各状态和回调函数使用

    回调函数 就像activities一样,fragments也有它们自己的生命周期.理解fragments的生命周期,可以使你在它们被销毁的时候保存它们的实例,这样在它们重新被创建的时候,就能恢复它们之前的状态. 流程: onAttach() 作用:fragment已经关联到activity, 这个是 回调函数 @Override public void onAttach(Activity activity) { super.onAttach(activity); Log.i("onAttach_

  • Android基础之使用Fragment控制切换多个页面

    今天讲解一下Fragment的控制,主要是切换View和页面替换等操作.还有就是如何获取Fragment的管理对象,以及与Activity的通信方式.1.管理Fragment要在activity中管理fragment,需要使用FragmentManager. 通过调用activity的getFragmentManager()取得它的实例. •可以通过FragmentManager做一些事情, 包括: 使用findFragmentById()(用于在activity layout中提供一个UI的f

  • Android 管理Activity中的fragments

    FragmentManager 为了管理Activity中的fragments,需要使用FragmentManager. 为了得到它,需要调用Activity中的getFragmentManager()方法. 因为FragmentManager的API是在Android 3.0,也即API level 11开始引入的,所以对于之前的版本,需要使用support library中的FragmentActivity,并且使用getSupportFragmentManager()方法. 用Fragme

  • Android中fragment嵌套fragment问题解决方法

    都说fragment好用,duang~~,又遇到问题了,记录一下,分享给遇到这个问题的同学! 1.fragment嵌套fragment时出现getActivity()为null activity A嵌套fragment B,B嵌套fragment C,C跳转到activity D,当activity D被finish掉之后,C中容易爆出getActivity为空.如果你的activity被回收了,那你需要在bundle中保存一下fragment信息,我的解决方法:fragment实例化之后会到a

  • Android应用开发中Fragment的静态加载与动态加载实例

    1.Fragment的静态使用 Fragment是作为Activity的UI的一部分,它内嵌在Activity中,多个Fragment可以把一个Activity分成多个部分,这在大屏幕手机或者平板电脑中会比较多的用到,这样就不用使用多个Activity来切换这么麻烦了.当然Fragment也可以不显示,只在后台处理一些数据,这篇文章中就暂时不谈到这个.以下来看怎么静态地在Activity的布局文件中添加Fragment. 自定义的Fragment通常要继承Fragment这个类,也有一些特殊的是

  • Android App中ViewPager与Fragment结合的一些问题解决

    在了解ViewPager的工作原理之前,先回顾ListView的工作原理: ListView只有在需要显示某些列表项时,它才会去申请可用的视图对象:如果为所有的列表项数据创建视图对象,会浪费内存: ListView找谁去申请视图对象呢? 答案是adapter.adapter是一个控制器对象,负责从模型层获取数据,创建并填充必要的视图对象,将准备好的视图对象返回给ListView: 首先,通过调用adapter的getCount()方法,ListView询问数组列表中包含多少个对象(为避免出现数组

  • Android Map新用法:MapFragment应用介绍

    1.MapView ,MapActivity 这种的局限在于,必须要继承MapActivity,否则无法使用MapView.纠结就在于此.但是,最新官网上已经弃用了这糟粕的MapActivity. Version 1 of the Google Maps Android API as been officially deprecated as of December 3rd, 2012. This means that from March 3rd, 2013 you will no longe

  • Android中Fragment 真正的完全解析(上)

    自从Fragment出现,曾经有段时间,感觉大家谈什么都能跟Fragment谈上关系,做什么都要问下Fragment能实现不~~~哈哈,是不是有点过~~~ 本文力求为大家说明Fragment如何产生,什么是Fragment,Fragment生命周期,如何静态和动态的使用Fragment,Fragment回退栈,Fragment事务:以及Fragment的一些特殊用途,例如:没有布局的Fragment有何用处?Fragment如何与Activity交互?Fragment如何创建对话框?Fragme

  • Android 中 Fragment的使用大全

    Fragment必须总是被嵌入到一个Activity中,并且它的生命周期直接受宿主Activity生命周期的影响. 本文内容可以分为下面的几部分: 使用支持库 创建一个Fragment 创建一个动态UI 多个Fragment之间的通信 在一个Activity中,一个Fragment代表一种行为或者用户界面的一部分.你可以联合起来多个Fragment在一个Activity中创建多面板的UI,并且可以重用一个Fragment在多个activity中.你可以认为一个Fragment是一个Activit

  • 详解Android中fragment和viewpager的那点事儿

    在之前的博文<Android 中使用 ViewPager实现屏幕页面切换和页面轮播效果>和<详解Android中Fragment的两种创建方式>以及<Android中fragment与activity之间的交互(两种实现方式)>中我们介绍了ViewPager以及Fragment各自的使用场景以及不同的实现方式. 那如果将他们两结合起来,会不会擦出点火花呢,答案是肯定的.之前在介绍ViewPager时,我们实现了多个ImageView的切换,并配合更新导航原点的状态.那我

  • Android中Fragment的基本用法示例总结

    前言 fragment 可认为是一个轻量级的Activity,但不同与Activity,它是要嵌到Activity中来使用的,它用来解决设备屏幕大小的不同,主要是充分利用界面上的空间,如平板上多余的空间.一个Activity可以插入多个Fragment,可以认为Fragment就是Activity上的一个View. 本文主要介绍了关于Android中Fragment的基本用法,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧. 一.fragment管理 在activity动态加载f

  • Android 中Fragment与Activity通讯的详解

    Android 中Fragment与Activity通讯的详解 与activity通讯 尽管fragment的实现是独立于activity的,可以被用于多个activity,但是每个activity所包含的是同一个fragment的不同的实例. Fragment可以调用getActivity()方法很容易的得到它所在的activity的对象,然后就可以查找activity中的控件们(findViewById()). 例如: ViewlistView =getActivity().findView

  • Android中fragment与activity之间的交互(两种实现方式)

    (未给Fragment的布局设置BackGound) 之前关于Android中Fragment的概念以及创建方式,我专门写了一篇博文<详解Android中Fragment的两种创建方式>,就如何创建Fragment混合布局做了详细的分析,今天就来详细说道说道Fragment与宿主Activity之间是如何实现数据交互的. 我们可以这样理解,宿主Activity中的Fragment之间要实现信息交互,就必须通过宿主Activity,Fragment之间是不可能直接实现信息交互的. Fragmen

  • Android中微信抢红包插件原理解析及开发思路

    一.前言 自从去年中微信添加抢红包的功能,微信的电商之旅算是正式开始正式火爆起来.但是作为Android开发者来说,我们在抢红包的同时意识到了很多问题,就是手动去抢红包的速度慢了,当然这些有很多原因导致了.或许是网络的原因,而且这个也是最大的原因.但是其他的不可忽略的因素也是要考虑到进去的,比如在手机充电锁屏的时候,我们并不知道有人已经开始发红包了,那么这时候也是让我们丧失了一大批红包的原因.那么关于网络的问题,我们开发者可能用相关技术无法解决(当然在Google和Facebook看来的话,他们

  • 详解Android中Fragment的两种创建方式

    fragment是Activity中用户界面的一个行为或者是一部分.你可以在一个单独的Activity上把多个Fragment组合成为一个多区域的UI,并且可以在多个Activity中再使用.你可以认为fragment是activity的一个模块零件,它有自己的生命周期,接收它自己的输入事件,并且可以在Activity运行时添加或者删除. 两个概念:Fragment.宿主 fragment的生命周期直接受其宿主activity的生命周期的影响.例如,一旦activity被暂停,它里面所有的fra

  • Android中Fragment的分屏显示处理横竖屏显示的实现方法

    演示效果如下: 另外在竖屏的时候是这样的效果: 布局文件如下: 可以看出有两个资源文件,一个是处理横屏一个是竖屏 第一个: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent&qu

  • Android中Fragment的加载方式与数据通信详解

    一.加载方式 1. 静态加载 1.1 加载步骤 (1) 创建fragment:创建自定义Fragment类继承自Fragment类,同时将自定义Fragment类与Fragment视图绑定(将layout转换成View) View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) inflater用于绑定Fragment的布局文件,同时将该布局转换成View对象并返回:con

随机推荐