Fragment是在API 11(Android3.0)引入的,为了能够支持适配宽屏设备,提供灵活多变的UI设计。
Fragment是嵌在Activity里面能够交互的用户界面,它的存在必须依赖于Activity,不能独立存在。
多个Activity可以复用同一个Fragment。一个Activity可以嵌入多个Fragment。
Fragment的生命周期如上图所示。
加入Activity的话则如上图所示。
如果不加入Activity的生命周期的话,则为: onAttach()->onCreate()->onCreateView()->onStart()->onResume()->Fragment处于活动状态 onPause()->onStop()->onDestroyView()->onDestroy()->onDetach()
其中onDestroyView()->onCreateView(),发生此种情况的条件是当Fragment从回退栈(back stack)返回时才会发生。例如:Activity启动了Fragment A,然后又启动了FragmentB替换了Fragment A并把A添加到回退栈,当B返回后,退回到A,A的生命周期从onDestroyView()->onCreateView()开始。
onCreate(),可以在这里进行初始化
onCreateView(),开始对Fragment界面进行绘制,需要返回一个View,通常为Fragment的布局。
onPause(),当调用到此方法时,说明用户正在离开Fragment,在这里需要对数据和状态进行保存
启动:
宿主BaseActivity切换到后台(Activity不可见):
宿主BaseActivity切换回前台:
宿主BaseActivity销毁:
通常的只需要继承实现Fragment类,为了保证兼容性,一般使用support包的Fragment。
- public
- class
- BaseFragment
- extends
- Fragment
- {
- onCreate(){
- }
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- // Inflate the layout for this fragment
- return inflater.inflate(R.layout.fragment_article_list, container, false);
- }
- }
- <?
- xml version=
- "1.0"
- encoding=
- "utf-8"
- ?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="horizontal"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
- <fragment android:name="com.example.news.ArticleListFragment"
- android:id="@+id/list"
- android:layout_weight="1"
- android:layout_width="0dp"
- android:layout_height="match_parent" />
- <fragment android:name="com.example.news.ArticleReaderFragment"
- android:id="@+id/viewer"
- android:layout_weight="2"
- android:layout_width="0dp"
- android:layout_height="match_parent" />
- </LinearLayout>
其中中的android:name属性的值为Fragment的类全名。
此时Activity可直接加载布局中的Fragment
为了给Fragment设定一个唯一的标识,可以使用如下两种方式:
设置唯一标识可以对数据恢复有帮助。
可以通过指定Activity布局中的ViewGroup布局来放置Fragment。
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
- ...
- <FrameLayout
- android:id="@+id/fl_fragment"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"/>
- ...
- </LinearLayout>
Activity建议使用扩展包中的FragmentActivity的子类
- public
- class
- BaseActivity
- extends
- FragmentActivity
- {
- ...
- //获取FragmentTransaction
- FragmentManager fragmentManager = getSupportFragmentManager();
- FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
- ...
- //添加Fragment
- BaseFragment fragment = new BaseFragment();
- fragmentTransaction.add(R.id.fl_fragment, fragment);
- fragmentTransaction.commit();
- ...
- }
此外,还可以通过FragmentTransaction的add的重载方法add(Fragment fragment,String tag)添加无界面的Fragment。此时的tag参数为Fragment的标识ID,要取唯一值。并且不需要实现onCreateView()。由于此时Fragment无界面,所以不会对Activity的当前界面造成影响。
如果需要获取到无界面Fragment,可以使用fragmentManager.findFragmentByTag(tag)。
可以使用FragmentTransaction对Fragment进行管理,进行
操作完后必须调用commit()才会生效。
一次典型的操作:
- Fragment newFragment = new BaseFragment();
- FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
- //替换成新的Fragment
- transaction.replace(R.id.fragment_container, newFragment);
- //把当前的FragmentTransaction加入到回退栈
- transaction.addToBackStack(null);
- // Commit the transaction
- transaction.commit();
transaction.addToBackStack(null);的作用是把当前FragmentTransaction加入到回退栈,当执行此代码并commit后,则点击回退键Activity不会直接结束,而是返回到Activity界面
有几个点需要注意:
下图为Fragment的返回栈,当前的FragmentTransaction实例调用addToBackStack()并commit就会入栈:
返回的话会从栈顶开始返回,最上层的会销毁
一个Fragment的实例是和它所绑定的Activity实例紧紧关联的。Fragment可以通过getActivity()获取它所关联绑定的Activity。
宽屏布局 res/layout-land/fragment_layout.xml,用于大屏幕设备,比如平板电脑等:
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="horizontal"
- android:layout_width="match_parent" android:layout_height="match_parent">
- <fragment class="com.example.android.apis.app.FragmentLayout$TitlesFragment"
- android:id="@+id/titles" android:layout_weight="1"
- android:layout_width="0px" android:layout_height="match_parent" />
- <FrameLayout android:id="@+id/details" android:layout_weight="1"
- android:layout_width="0px" android:layout_height="match_parent"
- android:background="?android:attr/detailsElementBackground" />
- </LinearLayout>
手机布局 res/layout/fragment_layout.xml:
- <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent" android:layout_height="match_parent">
- <fragment class="com.example.android.apis.app.FragmentLayout$TitlesFragment"
- android:id="@+id/titles" android:layout_width="match_parent" android:layout_height="match_parent"
- />
- </FrameLayout>
TitlesFragment 的实现
- public static
- class
- TitlesFragment
- extends
- ListFragment
- {
- boolean mDualPane;
- int mCurCheckPosition = 0;
- @Override
- public
- void
- onActivityCreated
- (Bundle savedInstanceState)
- {
- super.onActivityCreated(savedInstanceState);
- // 添加文章列表
- setListAdapter(new ArrayAdapter<String>(getActivity(),
- android.R.layout.simple_list_item_activated_1, Shakespeare.TITLES));
- // 检查是否上图左边的那种布局(宽屏模式)
- View detailsFrame = getActivity().findViewById(R.id.details);
- mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;
- if (savedInstanceState != null) {
- // Restore last state for checked position.
- mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
- }
- if (mDualPane) {
- // In dual-pane mode, the list view highlights the selected item.
- getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
- // Make sure our UI is in the correct state.
- showDetails(mCurCheckPosition);
- }
- }
- @Override
- public
- void
- onSaveInstanceState
- (Bundle outState)
- {
- super.onSaveInstanceState(outState);
- outState.putInt("curChoice", mCurCheckPosition);
- }
- @Override
- public
- void
- onListItemClick
- (ListView l, View v, int position, long id)
- {
- showDetails(position);
- }
- /**
- * 如果是宽屏模式的话,则直接在右边的Fragment更新内容
- * 如果不是宽屏模式,则跳转到新的Activity进行展示
- */
- void
- showDetails
- (int index)
- {
- mCurCheckPosition = index;
- if (mDualPane) {
- getListView().setItemChecked(index, true);
- DetailsFragment details = (DetailsFragment)
- getSupportFragmentManager().findFragmentById(R.id.details);
- if (details == null || details.getShownIndex() != index) {
- details = DetailsFragment.newInstance(index);
- FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
- if (index == 0) {
- ft.replace(R.id.details, details);
- } else {
- ft.replace(R.id.a_item, details);
- }
- ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
- ft.commit();
- }
- } else {
- Intent intent = new Intent();
- intent.setClass(getActivity(), DetailsActivity.class);
- intent.putExtra("index", index);
- startActivity(intent);
- }
- }
- }
DetailsFragment的实现:
- public static
- class
- DetailsFragment
- extends
- Fragment
- {
- public
- static
- DetailsFragment
- newInstance
- (int index)
- {
- DetailsFragment f = new DetailsFragment();
- Bundle args = new Bundle();
- args.putInt("index", index);
- f.setArguments(args);
- return f;
- }
- public
- int
- getShownIndex
- ()
- {
- return getArguments().getInt("index", 0);
- }
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- if (container == null) {
- // We have different layouts, and in one of them this
- // fragment's containing frame doesn't exist. The fragment
- // may still be created from its saved state, but there is
- // no reason to try to create its view hierarchy because it
- // won't be displayed. Note this is not needed -- we could
- // just run the code below, where we would create and return
- // the view hierarchy; it would just never be used.
- return null;
- }
- ScrollView scroller = new ScrollView(getActivity());
- TextView text = new TextView(getActivity());
- int padding = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
- 4, getActivity().getResources().getDisplayMetrics());
- text.setPadding(padding, padding, padding, padding);
- scroller.addView(text);
- text.setText(Shakespeare.DIALOGUE[getShownIndex()]);
- return scroller;
- }
- }
如果是手机的情况,跳转到新的Activity:
- public static
- class
- DetailsActivity
- extends
- FragmentActivity
- {
- @Override
- protected
- void
- onCreate
- (Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- if (getResources().getConfiguration().orientation
- == Configuration.ORIENTATION_LANDSCAPE) {
- // If the screen is now in landscape mode, we can show the
- // dialog in-line with the list so we don't need this activity.
- finish();
- return;
- }
- if (savedInstanceState == null) {
- // During initial setup, plug in the details fragment.
- DetailsFragment details = new DetailsFragment();
- details.setArguments(getIntent().getExtras());
- getSupportFragmentManager().beginTransaction().add(android.R.id.content, details).commit();
- }
- }
- }
--End--
来源: https://juejin.im/post/5a235cfc6fb9a044fa19ad2e