Fragment精炼详解

一、前期基础知识储备

(1上官方文档Fragment

public class Fragment.A Fragment is a piece of an application's user interface or behavior that can be placed in an Activity. Interaction with fragments is done through FragmentManager, which can be obtained via Activity.getFragmentManager() and Fragment.getFragmentManager().

The Fragment class can be used many ways to achieve a wide variety of results. In its core, it represents a particular operation or interface that is running within a larger Activity. A Fragment is closely tied to the Activity it is in, and can not be used apart from one. Though Fragment defines its own lifecycle, that lifecycle is dependent on its activity: if the activity is stopped, no fragments inside of it can be started; when the activity is destroyed, all fragments will be destroyed.

2)Fragement碎片是什么:碎片是一种可以嵌入活动中的UI片段,它能让程序更加合理和充分的利用大屏幕的控件,因而在平板上应用的非常广泛。虽然碎片是全新的概念,但是学起来却会比较简单,因为碎片和活动实在是太像了,同样能包含布局,同样都有自己的生命周期(碎片的生命周期和活动的非常像)。你甚至可以将碎片理解为一个迷你型的活动,虽然这个迷你型的活动有可能和普通的活动一样大。Android自3.0版本(2011年)引入了碎片的概念,它可以让界面在平板上更好的展示,参见官方给出的示例:

                           Fragment精炼详解

现在的开发主要是使用碎片的对活动分片功能,通过对Activity布局进行分片,更加方便的对每块进行独立控制。而且这些片段可以被不同的Activity复用。比如下面新闻app的底部导航栏部分,就是采用碎片的方式实现不同界面的切换

                             Fragment精炼详解Fragment精炼详解

(2)Fragment的生命周期图

                              Fragment精炼详解

说明①Fragment需要嵌套在Activity中使用,当然也可以嵌套到另外一个Fragment中,但这个被嵌套 的Fragment也是需要嵌套在Activity中的,间接地说,Fragment还是需要嵌套在Activity中!! 受寄主Activity的生命周期影响,当然他也有自己的生命周期!另外不建议在Fragment里面 嵌套Fragment因为嵌套在里面的Fragment生命周期不可控!!!

②官方文档说创建Fragment时至少需要实现三个方法:onCreate( ),onCreateView( ),OnPause( ); 不过实际开发中大多只写一个onCreateView也是可以的...

③Fragment的生命周期和Activity有点类似:四种状态:

运行状态:在运行中的Fragment可见;

暂停状态:所在Activity可见,但是得不到焦点;

停止状态: ①调用addToBackStack(),Fragment被添加到Bcak栈 ②该Activity转向后台,或者该Fragment被替换/删除;

销毁状态碎片总是依附于活动而存在的,因此当活动被销毁时,与它相关联的碎片就会进入销毁状态

同样地,碎片也提供了一系列的回调方法。其中,活动的回调方法,碎片中几乎都有,不过碎片还提供了一些附加的回调方法:

  • onAttcah(),当碎片和活动建立关联时调用。
  • onCreateView(),为碎片创建视图(加载布局)时调用。
  • onActivityCreated(),确保与碎片相关联的活动一定已经创建完毕时调用。
  • onDestroyView(),当与碎片想关联的视图被移除时调用。
  • onDetach(),当碎片和活动解除关联时调用。

(3)其他前期知识①很多时候我们都是直接重写Fragment,inflate加载布局完成相应业务,碎片子类用的不多;②推荐使用V4包下的碎片,因为它可以让碎片在所有Android系统中保持功能一致性。

二、创建一个碎片

碎片有两种加载方式:①静态加载②动态加载

①静态加载碎片—简单

                          Fragment精炼详解

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment1, container,false);
        return view;
    }   

};

———————————————————我是分割线—————————————————

<fragment
    android:id="@+id/fragment1"
    android:name="com.jay.example.fragmentdemo.Fragmentone"
    android:layout_width="match_parent"
    android:layout_height="0dp"

android:layout_weight="1" />

———————————————————我是分割线—————————————————

最后只要在主类文件中调用调用setContentView()加载布局文件即可!

②动态加载碎片—碎片真正强大之处,在需要的地方加载

                         Fragment精炼详解

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Display dis = getWindowManager().getDefaultDisplay();
        if(dis.getWidth() > dis.getHeight())
        {
            Fragment1 f1 = new Fragment1();
            getFragmentManager().beginTransaction().replace(R.id.LinearLayout1, f1).commit();
        }
        else
        {

           Fragment2 f2 = new Fragment2();            

            getFragmentManager().beginTransaction().replace(R.id.LinearLayout1, f2).commit();

        }//写法简单干脆,且理解也比较到位。
    }   

};

三、活动和碎片的交互

                          Fragment精炼详解

实例实现碎片传递数据给活动,在Fragment中定义一个内部回调接口,再让包含该Fragment的Activity实现该回调接口, Fragment就可以通过回调接口传数据了,回调。分三步走:

①定义一个回调接口:(Fragment中)

//接口

public interface CallBack{  

    /*定义一个获取信息的方法*/  

    public void getResult(String result);  

} ;

②接口回调(Fragment中)

//接口回调  

public void getData(CallBack callBack){  

    /*获取文本框的信息,当然你也可以传其他类型的参数,看需求咯*/  

    String msg = editText.getText().toString();  

    callBack.getResult(msg);  

} ;

③使用接口回调方法读数据(Activity中)

//使用接口回调的方法获取数据

leftFragment.getData(new CallBack() {  

  @Override  

       public void getResult(String result) {              

            Toast.makeText(MainActivity.this, + result, 1).show();  

            }//此处涉及匿名内部类,继承自接口,必须实现接口指定的方法

});

总结

  • 在Fragment定义一个接口,接口中定义抽象方法,你要传什么类型的数据参数就设置为什么类型;
  • 接着还有写一个调用接口中的抽象方法,把要传递的数据传过去
  • 再接着就是Activity了,调用Fragment提供的那个方法,然后重写抽象方法的时候进行数据 的读取就可以了!!!