Fragment总结(一)

我们日常开发中经常会使用到fragment,通常会放置在主页面上,方便切换展示信息。它拥有自己的生命周期,可以接受处理用户的事件,并且你可以在一个Activity中动态的添加,替换,移除不同的Fragment。

一、生命周期

第一张图展示了fragment的生命周期,第二章图展示了 Activity 与 Fragment 生命周期的对比

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

  • onAttach(Activity) 当Fragment与Activity发生关联的时候调用(在这个方法中可以获得所在的activity)

  • onCreateView(LayoutInflater, ViewGroup, Bundle) 创建该Fragment的视图

  • onActivityCreated(Bundle) 当Activity的onCreated方法返回时调用

  • onDestroyView() 与onCreateView方法相对应,当该Fragment的视图被移除时调用

  • onDetach() 与onAttach方法相对应,当Fragment与Activity取消关联时调用

一旦activity进入resumed状态(也就是running状态),你就可以自由地添加和删除fragment了。因此,只有当activity在resumed状态时,fragment的生命周期才能独立的运转,其它时候是依赖于activity的生命周期变化的。

二、使用

1.静态使用

步骤:

  1. 创建一个类继承Fragment,重写onCreateView方法,来确定Fragment要显示的布局
  2. 在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 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>

2.动态使用

步骤:

  1. 编写不同的fragment界面和类
  2. 在activity使用FragmentManager对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>

继承Fragment的类MyFragment2

public class MyFragment2 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);
    }

}

FragmentTransaction的方法主要有以下几种:

  • 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() 提交事务

三、回退栈

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

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

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

  • 输入change,点击按钮,显示第三个Fragment,上面有个Button in FragmentThree,点击按钮显示出一个Toast

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

  • 【注意】再点击返回键,跳转到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包下的】

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();
    }

}

FragmentOne.java文件

public class FragmentOne extends Fragment implements OnClickListener {

    private Button mBtn;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_one, container, false);
        mBtn = (Button) view.findViewById(R.id.id_fragment_one_btn);
        mBtn.setOnClickListener(this);
        return view;
    }

    @Override
    public void onClick(View v) {
        FragmentTwo fTwo = new FragmentTwo();
        FragmentManager fm = getFragmentManager();
        FragmentTransaction tx = fm.beginTransaction();
        tx.replace(R.id.id_content, fTwo, "TWO");
        tx.addToBackStack(null);
        tx.commit();
    }

}

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

FragmentTwo.java文件

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, container, false);
        mBtn = (Button) view.findViewById(R.id.id_fragment_two_btn);
        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.addToBackStack(null);
        tx.commit();
    }

}

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

FragmentThree.java文件

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, container, 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 three",
                Toast.LENGTH_SHORT).show();
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章