Fragment

可重用的activity中的模块,避免activity切换,有自己的生命周期、状态、back stack。

3.0引入Fragment目的:支持大屏幕中动态灵活的UI设计。

1、实质:在onCreateView()中返回的是view;类似自我实现的view栈。DialogFragment类似自我实现的dialog栈。优点:加入了显式的生命周期。

2、添加fragment到activity:

  xml的layout中每个<fragment>需要赋予唯一的android:id/tag(非ui);

3、FragmentTransaction:一系列fragment操作add、remove、replace,addToBackStack()支持undo,setTransition()可以设置fragment切换动画,然后commit;

4、fragment调activity:getActivity()

  activity调fragment:getFragmentManager().findFragmentById(R.id)

  回调:在fragment中声明interface, activity实现该interface, 在fragment的onAttach()中拥有interface(即实现了interface的activity)成员。

5、menu:在onCreate()中setHasOptionsMenu(),然后实现onCreateOptionsMenu()、onOptionsItemSelected();需注意activity先收到selected事件。

  上下文菜单:registerForContextMenu()、onCreateContextMenu()、onContextItemSelected()。

6、向前兼容: 使用support jar包, 所有的Fragment等类名相同,但要import support包名;

原文地址:https://www.cnblogs.com/toven/p/2608168.html