With Android learn of Fragment

Outline

In this paper, a simple small example, outlined in Android development, Fragment of common usage, only to learn to share, if any inadequacies, please correct me.

What is Fragment?

Fragment represent a part of a function or user interface. A Activity may be composed of a plurality of Fragment composed of a multi-pane the UI , a Fragment may be reused in a plurality of Activity in. You can put Fragment as Activity of a module, it has its own life cycle, to receive their input event when Activity runtime can dynamically add and remove, similar to ' Sub Activity '.

Fragment must always be as Activity part of its life cycle by the host Activity affect the life cycle. Such as: When Activity is paused, all of its contained Fragment are also suspended; when Activity when destroyed, all it contains Fragment will be destroyed; but when the Activity is running, you can separate operations Fragment, such as adding and deleting;

Fragment design

android in android 3.0 ( API level 11 was introduced in) Fragment , primarily to support the big screen (such as tablets) on a more dynamic and flexible ui design. Because the tablet screen is much larger than a cell phone, so there is more room to combine and exchange ui components. By Activity layout is divided into Fragment , will be able to modify the program runs Activity appearance, and save the changes made after the stack in campaign management.

For example, a news application App , you can use a Fragment display the article list on the left, with another Fragment article on the right shows ---- two Fragment also appear in a Activity in, and each Fragment has its own life cycle callback methods and the collection and processing their own user input events. Accordingly, the user may be the same Activity selected article, rather than be used separately in different Activity , as shown in a flat layout shown in FIG.

Each should Fragment designed to be modular and reusable page components. In other words, since each Fragment has its own life cycle, the callback function, layout and behaviors, it can be more Activity included in the same Fragment . Fragment should be designed to reuse, to avoid a Fragment direct reference to another operating Fragment . This is particularly important, because a modular Fragment can adapt to different screen sizes by different combinations. When the application supports both tablets and phones, can be reused in different layout configurations Fragment , to optimize the user experience according to screen space.

FIG 1 an example of how the two Fragment defined UI how to design a flat plate modules on Activity display, but are shown separately on the phone.

Involving knowledge points

Involving knowledge points are as follows:

  • Fragment all custom Fragment of the parent class.
  • FragmentManager Fragment manager object, to dynamically add and replace Fragmentd objects.
  • FragmentTransaction represents a Fragment of Management, must commit () end.
  • onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) method returns Fragment corresponding layout view.
  • getFragmentManager () Returns a Fragment manager object.

Creating a Fragment

If you want to create a custom Fragment , you must create a Fragment subclass must implement and onCreateView () method, by LayoutInflater filling the layout file into Fragment , as follows:

 1 public class RightFragment extends Fragment {
 2 
 3     private TextView tvMsg;
 4 
 5     @Override
 6     public View onCreateView(LayoutInflater inflater, ViewGroup container,
 7                              Bundle savedInstanceState) {
 8         // Inflate the layout for this fragment
 9         Log.i("TAG", "------------Right-----------onCreateView: ");
10         View view= inflater.inflate(R.layout.fragment_right, container, false);
11         tvMsg= (TextView) view.findViewById(R.id.tv_msg);
12         return view;
13     }
14 }

Fragment life cycle

Fragment of the life cycle and the Activity life cycle has many similarities. As shown below:

Activity and Fragment callback outputting content as follows:

 1 05-30 22:16:02.207 29479-29479/com.hex.demofragment I/TAG: ------------Left-----------onAttach: 
 2 05-30 22:16:02.207 29479-29479/com.hex.demofragment I/TAG: ------------Left-----------onCreate: 
 3 05-30 22:16:02.207 29479-29479/com.hex.demofragment I/TAG: ------------Left-----------onCreateView: 
 4 05-30 22:16:02.216 29479-29479/com.hex.demofragment I/TAG: ------------Right-----------onAttach: 
 5 05-30 22:16:02.216 29479-29479/com.hex.demofragment I/TAG: ------------Right-----------onCreate: 
 6 05-30 22:16:02.216 29479-29479/com.hex.demofragment I/TAG: ------------Right-----------onCreateView: 
 7 05-30 22:16:02.218 29479-29479/com.hex.demofragment E/TAG: ------------Main-----------onCreate: 
 8 05-30 22:16:02.218 29479-29479/com.hex.demofragment I/TAG: ------------Left-----------onActivityCreated: 
 9 05-30 22:16:02.218 29479-29479/com.hex.demofragment I/TAG: ------------Right-----------onActivityCreated: 
10 05-30 22:16:02.219 29479-29479/com.hex.demofragment E/TAG: ------------Main-----------onStart: 
11 05-30 22:16:02.219 29479-29479/com.hex.demofragment I/TAG: ------------Left-----------onStart: 
12 05-30 22:16:02.219 29479-29479/com.hex.demofragment I/TAG: ------------Right-----------onStart: 
13 05-30 22:16:02.224 29479-29479/com.hex.demofragment E/TAG: ------------Main-----------onResume: 
14 05-30 22:16:02.224 29479-29479/com.hex.demofragment I/TAG: ------------Left-----------onResume: 
15 05-30 22:16:02.224 29479-29479/com.hex.demofragment I/TAG: ------------Right-----------onResume: 
16 05-30 22:16:06.188 29479-29479/com.hex.demofragment I/TAG: ------------Left-----------onPause: 
17 05-30 22:16:06.188 29479-29479/com.hex.demofragment I/TAG: ------------Right-----------onPause: 
18 05-30 22:16:06.189 29479-29479/com.hex.demofragment E/TAG: ------------Main-----------onPause: 
19 05-30 22:16:06.756 29479-29479/com.hex.demofragment I/TAG: ------------Left-----------onStop: 
20 05-30 22:16:06.756 29479-29479/com.hex.demofragment I/TAG: ------------Right-----------onStop: 
21 05-30 22:16:06.756 29479-29479/com.hex.demofragment E/TAG: ------------Main-----------onStop: 
22 05-30 22:16:06.757 29479-29479/com.hex.demofragment I/TAG: ------------Left-----------onDestroyView: 
23 05-30 22:16:06.757 29479-29479/com.hex.demofragment I/TAG: ------------Left-----------onDestroy: 
24 05-30 22:16:06.757 29479-29479/com.hex.demofragment I/TAG: ------------Left-----------onDetach: 
25 05-30 22:16:06.757 29479-29479/com.hex.demofragment I/TAG: ------------Right-----------onDestroyView: 
26 05-30 22:16:06.757 29479-29479/com.hex.demofragment I/TAG: ------------Right-----------onDestroy: 
27 05-30 22:16:06.757 29479-29479/com.hex.demofragment I/TAG: ------------Right-----------onDetach: 
28 05-30 22:16:06.757 29479-29479/com.hex.demofragment E/TAG: ------------Main-----------onDestroy: 
View Code

Activity中添加Fragment

Fragment是作为Activity的一部分而存在的,有两种方法可以将Fragment添加到Activity的布局文件中:

静态添加Fragment

Activity的布局文件中直接声明Fragment,在这种情况下,您可以为Fragment指定布局属性,就像它是视图控件一样。例如,这里是包含两个片段的活动的布局文件:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout
 3     xmlns:android="http://schemas.android.com/apk/res/android"
 4     xmlns:tools="http://schemas.android.com/tools"
 5     android:layout_width="match_parent"
 6     android:layout_height="match_parent"
 7     android:orientation="horizontal"
 8     tools:context="com.hex.demofragment.MainActivity">
 9    <fragment
10        android:tag="left"
11        android:id="@+id/left_fragment"
12        class="com.hex.demofragment.LeftFragment"
13        android:layout_width="200dp"
14        android:layout_height="match_parent"
15        android:layout_weight="1"></fragment>
16     <fragment
17         android:tag="right"
18         android:id="@+id/right_fragment"
19         class="com.hex.demofragment.RightFragment"
20         android:layout_width="300dp"
21         android:layout_height="match_parent"
22         android:layout_weight="2"></fragment>
23 </LinearLayout>

如上所示:class 表示需要在视图中显示的fragment类,当系统创建Activity时,就会实例化Fragment并调用onCreateView方法,显示对应的布局文件。android:name和class表示的功能是一样的,需要其中一个即可。

备注:每个Fragment都需要一个唯一的标识符,如果Activity被重新启动的话,系统可以用它来恢复Fragment。

有三种方法可以为Fragment提供id:

  • 提供android:id带有唯一的ID属性。
  • 提供android:tag带有唯一字符串的标签属性。
  • 如果没有提供前面两个中的任何一个,系统将使用容器视图的id。
动态添加Fragment

Activity处于运行状态时,都可以将Fragment添加到页面布局中,只需要有一个ViewGroup用来存放即可。如下所示:

 1 //FragmentManager是Activity内部用来与Fragment进行交互的接口
 2 FragmentManager fm =  getFragmentManager();
 3 FragmentTransaction  ft=fm.beginTransaction();
 4 //将左侧Fragment和Frame控件关联起来
 5 left=new LeftFragment();
 6 left.setTransData(transData);
 7 ft.add(R.id.fl_left,left);
 8 right=new RightFragment();
 9 ft.add(R.id.fl_right,right);
10 ft.commit();

如果要管理Activity中的Fragment,需要使用碎片管理器(FragmentManager),可以通过Activity中的getFragmentManager()方法来获得对象。

Fragment之间的传值

Fragment 作为独立的可重用的用户模块,应尽量避免相互引用,所以如何实现之间相互传值,就显得很重要,本文采用接口回调的方式进行传值。

具体如下:

1、定义一个传值接口,如下所示:

1 public interface ITransData {
2     public void transData(Bundle bundle);
3 }

2、在需要传值的Fragment中,定义接口属性对象,如下所示,左侧(LeftFragment):

 1 private ITransData mTransData;
 2 
 3 public void setTransData(ITransData transData){
 4     this.mTransData=transData;
 5 }
 6 
 7 @Override
 8 public View onCreateView(LayoutInflater inflater, ViewGroup container,
 9                          Bundle savedInstanceState) {
10 
11     View view = inflater.inflate(R.layout.fragment_left, container, false);
12     Button tv= (Button) view.findViewById(R.id.bn_left);
13     tv.setOnClickListener(new View.OnClickListener() {
14         @Override
15         public void onClick(View v) {
16             if(mTransData!=null){
17                 Bundle bundle=new Bundle();
18                 bundle.putString("name","我是左边");
19                 mTransData.transData(bundle);
20             }
21         }
22     });
23     return view;
24 }

3、Activity中,实现ITransData接口,并传给LeftFragment进行调用:

 1 @Override
 2 protected void onCreate(Bundle savedInstanceState) {
 3     super.onCreate(savedInstanceState);
 4     setContentView(R.layout.activity_main2);
 5     ITransData transData=new TransData();
 6     //FragmentManager是Activity内部用来与Fragment进行交互的接口
 7     FragmentManager fm =  getFragmentManager();
 8     FragmentTransaction  ft=fm.beginTransaction();
 9     //将左侧Fragment和Frame控件关联起来
10     left=new LeftFragment();
11     left.setTransData(transData);//将接口传递给LeftFragment
12     ft.add(R.id.fl_left,left);
13     right=new RightFragment();
14     ft.add(R.id.fl_right,right);
15     ft.commit();
16 }

4、在接口函数中调用获取左侧传回来的值,并调用RightFragment方法传递值。

 1 protected class TransData implements ITransData
 2 {
 3     @Override
 4     public void transData(Bundle bundle) {
 5         String name=bundle.getString("name","空");
 6         if(right!=null){
 7             right.setTransData(name);
 8         }
 9     }
10 }

至此Fragment之间传值介绍完毕,总结一句话:Fragment通过接口传值,接口的实现在Activity中,实现松耦合。

备注

沧海月明珠有泪,蓝田日暖玉生烟。

Guess you like

Origin www.cnblogs.com/hsiang/p/10960598.html