Android中Fragment的解析

一、Fragment详解

1. 什么是Fragment ?

你可以简单的理解为,Fragment是显示在Activity中的Activity。它可以显示在Activity中,然后它也可以显示出一些内容。因为它拥有自己的生命周期,可以接受处理用户的事件,并且你可以在一个Activity中动态的添加,替换,移除不同的 
Fragment,因此对于信息的展示具有很大的便利性。

2. Fragment的生命周期

因为Fragment是依附于Activity存在的,因此它的生命周期受到Activity的生命周期影响 
这里写图片描述

Fragment比Activity多了几个生命周期的回调方法

  • onAttach(Activity) 当Fragment与Activity发生关联的时候调用
  • onCreateView(LayoutInflater, ViewGroup, Bundle) 创建该Fragment的视图
  • onActivityCreated(Bundle) 当Activity的onCreated方法返回时调用
  • onDestroyView() 与onCreateView方法相对应,当该Fragment的视图被移除时调用
  • onDetach() 与onAttach方法相对应,当Fragment与Activity取消关联时调用

3. Fragment的使用方式

静态使用Fragment 
步骤:① 创建一个类继承Fragment,重写onCreateView方法,来确定Fragment要显示的布局 
② 在Activity中声明该类,与普通的View对象一样

代码演示 
MyFragment对应的布局文件item_fragment.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="@color/colorAccent"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:src="@mipmap/ic_launcher" />
</RelativeLayout>

继承Frgmanet的类MyFragment【请注意导包的时候导v4的Fragment的包】

public class MyFragment extends Fragment {
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        /*
        * 参数1:布局文件的id
        * 参数2:容器
        * 参数3:是否将这个生成的View添加到这个容器中去
        * 作用是将布局文件封装在一个View对象中,并填充到此Fragment中
        * */
        View v = inflater.inflate(R.layout.item_fragment, container, false);
        return v;
    }
}

Activity对应的布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.usher.fragment.MainActivity">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:gravity="center"
        android:text="Good Boy" />
    <fragment
        android:id="@+id/myfragment"
        android:name="com.usher.fragment.MyFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

动态使用Fragment

实现点击不同的按钮,在Activity中显示不同的Fragment 
代码演示 
Fragment对应的布局文件item_fragment.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="@color/colorAccent" //背景红色
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:src="@mipmap/ic_launcher" />
</RelativeLayout>

继承Frgmanet的类MyFragment

public class MyFragment extends Fragment {
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.item_fragment, container, false);
        return v;
    }
}

Fragment2对应的布局文件item_fragment2.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="@color/colorPrimary" //背景蓝色
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:src="@mipmap/ic_launcher" />
</RelativeLayout>

继承Fragment2的类

public class MyFragment extends Fragment {
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.item_fragment2, container, false);
        return v;
    }
}

MainActivity对应的布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.usher.fragment.MainActivity">
    <Button
        android:id="@+id/bt_red"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Red" />
    <Button
        android:id="@+id/bt_blue"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Blue" />
    <FrameLayout
        android:id="@+id/myframelayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

MainActivity类

public class MainActivity extends AppCompatActivity {
    private Button bt_red;
    private Button bt_blue;
    private FragmentManager manager;
    private MyFragment fragment1;
    private MyFragment2 fragment2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        fragment1 = new MyFragment();
        fragment2 = new MyFragment2();
        //初始化FragmentManager对象
        manager = getSupportFragmentManager();
        //使用FragmentManager对象用来开启一个Fragment事务
        FragmentTransaction transaction = manager.beginTransaction();
        //默认显示fragment1
        transaction.add(R.id.myframelayout, fragment1).commit();
        //对bt_red设置监听
        bt_red.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentTransaction transaction = manager.beginTransaction();
                transaction.replace(R.id.myframelayout, fragment1).commit();
            }
        });
        //对bt_blue设置监听
        bt_blue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentTransaction transaction = manager.beginTransaction();
                transaction.replace(R.id.myframelayout, fragment2).commit();
            }

        });
    }
    private void initView() {
        bt_red = (Button) findViewById(R.id.bt_red);
        bt_blue = (Button) findViewById(R.id.bt_blue);
    }
}

① 在Acitivity对应的布局中写上一个FramLayout控件,此空间的作用是当作Fragment的容器,Fragment通过FrameLayout显示在Acitivity里,这两个单词容易混淆,请注意

② 准备好你的Fragment,然后再Activity中实例化,v4包的Fragment是通过getSupportFragmentManager()方法新建Fragment管理器对象,此处不讨论app包下的Fragment

③ 然后通过Fragment管理器对象调用beginTransaction()方法,实例化FragmentTransaction对象,有人称之为事务

④ FragmentTransaction对象【以下直接用transaction代替】,transaction的方法主要有以下几种:

  • transaction.add() 向Activity中添加一个Fragment
  • transaction.remove() 从Activity中移除一个Fragment,如果被移除的Fragment没有添加到回退栈(回退栈后面会详细说),这个Fragment实例将会被销毁
  • transaction.replace() 使用另一个Fragment替换当前的,实际上就是remove()然后add()的合体
  • transaction.hide() 隐藏当前的Fragment,仅仅是设为不可见,并不会销毁
  • transaction.show() 显示之前隐藏的Fragment
  • detach() 会将view从UI中移除,和remove()不同,此时fragment的状态依然由FragmentManager维护
  • attach() 重建view视图,附加到UI上并显示
  • ransatcion.commit() 提交事务

注意:在add/replace/hide/show以后都要commit其效果才会在屏幕上显示出来

4. 什么是Fragment的回退栈?

Fragment的回退栈是用来保存每一次Fragment事务发生的变化 如果你将Fragment任务添加到回退栈,当用户点击后退按钮时,将看到上一次的保存的Fragment。一旦Fragment完全从后退栈中弹出,用户再次点击后退键,则退出当前Activity

首先来看一下这个东西: 

1.首先显示第一个FragmentOne页面有一个Button in FragmentOne,上面有个输入框显示的是Fragment One

2.然后输入change,点击Button in FragmentOne,然后显示第二个Fragment,里面有一个Button in FragmentTwo,一个输入框显示Fragment Two

3.输入change,点击按钮,显示第三个Fragment,上面有个Button inFragmentThree,点击按钮显示出一个Toast

4.【注意】点击返回键,跳转到前一个FragmentTwo,这个时候可以看到上面的输入框中显示的是Fragment Two change,也就是说保留了我们离开这个Fragment时候他所呈现的状态

5.【注意】再点击返回键,跳转到FragmentOne,但是这个时候我们可以看到上面的输入框中只有Fragment One,并没有change这几个字母

那么原因是什么? 
这里先要学习一个方法:FragmentTransaction.addToBackStack(String)【把当前事务的变化情况添加到回退栈】 
MainActivity的布局文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <FrameLayout
        android:id="@+id/id_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </FrameLayout>
</RelativeLayout>

MainActivity.java文件【这里添加的是app包下的Fragment,推荐v4包下的】Fragment详解

public class MainActivity extends Activity {
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        FragmentManager fm = getFragmentManager();
        FragmentTransaction tx = fm.beginTransaction();
        tx.add(R.id.id_content, new FragmentOne(),"ONE");
        tx.commit();
    }
}
Fragment的点击事件里写的是replace方法,相当于remove和add的合体,并且如果不添加事务到回退栈,前一个Fragment实例会被销毁。这里很明显,我们调用tx.addToBackStack(null)将当前的事务添加到了回退栈,所以FragmentOne实例不会被销毁,但是视图层次依然会被销毁,即会调用onDestoryView和onCreateView。所以【请注意】,当之后我们从FragmentTwo返回到前一个页面的时候,视图层仍旧是重新按照代码绘制,这里仅仅是是实例没有销毁,因此显示的页面中没有change几个字。

FragmentTwo.class文件

public class FragmentTwo extends Fragment implements OnClickListener {
    private Button mBtn ;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup
    container,Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_two, cont
    ainer, false);
    mBtn = (Button) view.findViewById(R.id.id_fragment_two_b
    tn);
    mBtn.setOnClickListener(this);
    return view ;
    }
    @Override
    public void onClick(View v) {
        FragmentThree fThree = new FragmentThree();
        FragmentManager fm = getFragmentManager();
        FragmentTransaction tx = fm.beginTransaction();
        tx.hide(this);
        tx.add(R.id.id_content , fThree, "THREE");
        //tx.replace(R.id.id_content, fThree, "THREE");
        tx.addToBackStack(null);
        tx.commit();
    }
}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

这里点击时,我们没有使用replace,而是先隐藏了当前的Fragment,然后添加了FragmentThree的实例,最后将事务添加到回退栈。这样做的目的是为了给大家提供一种方案:如果不希望视图重绘该怎么做,请再次仔细看效果图,我们在FragmentTwo的EditText填写的内容,用户点击返回键回来时,内容还在。

FragmentThree.class文件

public class FragmentThree extends Fragment implements OnClickListener {
    private Button mBtn;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup
    container,Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_three, co
        ntainer, false);
        mBtn = (Button) view.findViewById(R.id.id_fragment_three
        _btn);
        mBtn.setOnClickListener(this);
        return view;
    }
    @Override
    public void onClick(View v) {
        Toast.makeText(getActivity(), " i am a btn in Fragment t
        hree",Toast.LENGTH_SHORT).show();
    }
}

5. Fragment与Activity之间的通信

Fragment依附于Activity存在,因此与Activity之间的通信可以归纳为以下几点:

  • 如果你Activity中包含自己管理的Fragment的引用,可以通过引用直接访问所有的Fragment的public方法

  • 如果Activity中未保存任何Fragment的引用,那么没关系,每个Fragment都有一个唯一的TAG或者ID,可以通过getFragmentManager.findFragmentByTag()或者findFragmentById()获得任何Fragment实例,然后进行操作

  • Fragment中可以通过getActivity()得到当前绑定的Activity的实例,然后进行操作。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值