Android开发——UI_片段

书史足自悦,安用勤与劬。这篇文章主要讲述Android开发——UI_片段相关的知识,希望能为你提供帮助。

      • 创建片段
        • 片段类
        • 向活动中添加片段
      • 和活动之间通信
      • 片段的生命周期

片段是为了给大屏幕(比如平板电脑)提供更加灵活的UI支持。可以把它看作是子活动,必须嵌在活动中,并且有自己的生命周期,能接收自己的用户输入事件。当把片段作为活动布局的一部分添加时,片段会定义自己的视图布局。如何在活动的布局文件中添加片段呢?通过标签把片段作为活动的一个组件。
应该把每个片段都设计成可复用的模块化组件,避免直接从某个片段操纵另一个片段,这样可以把一个片段加入到多个活动中去。模块化组件使得根据屏幕大小自适应选择单窗口UI还是多窗口UI成为可能。以新闻应用为例,对平板可以在一个活动中添加列表片段和内容片段,而在手机中,一个活动中只有列表片段,点击之后出现包含内容片段的活动。
创建片段
片段类自定义片段必须继承自Fragment。创建片段一般至少实现以下生命周期方法:
  • onCreate():系统在创建片段时调用此方法。应该在此方法中初始化想在片段暂停或者停止后恢复时保留的组件。
  • onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState):此方法为片段加载其布局文件,系统在需要绘制片段布局时调用此方法。
    参数:
    inflater:用于加载布局文件
    container:片段布局将要插入的父ViewGroup,即活动布局。
    savedInstanceState:在恢复片段时,提供上一片段实例相关数据的Bundle
                    示例
public static class ExampleFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.example_fragment, container, false); } }

  • onPause():应该在此方法内确认用户会话结束后仍然有效的任何更改。
向活动中添加片段
  • 方法一:在活动的布局文件中声明片段
< ?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>

当系统创建此布局时,会实例化在布局中指定的每个片段,并为每个片段调用onCreateView()方法,以加载每个片段的布局。系统会以返回的View来替代< fragment > 元素。
  • 方法二:在源码中动态将片段添加到某个现有ViewGroup中
                要想在活动中执行片段事务,如添加、删除、替换片段,必须使用FragmentTransaction:
FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

                添加片段:
ExampleFragment fragment = new ExampleFragment(); fragmentTransaction.add(R.id.fragment_container, fragment); #第一个参数为片段插入到的视图 fragmentTransaction.commit();

和活动之间通信
在片段类中可以通过getActivity()得到和片段关联的活动实例;
在活动类中可以通过FragmentManager.findFragmentById()获取片段实例:
ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);

片段的生命周期
【Android开发——UI_片段】片段的生命周期和活动的生命周期类似,最大区别在于活动停止时会被放入由系统管理的活动返回栈中,而片段在移除事务执行期间,需要显式调用addToBackStack(),片段才会放入由活动管理的返回栈。
除了和活动一样的生命周期回调方法,片段还有几个额外的回调方法:
                onAttach():在片段与活动关联时调用;
                onCreateView():为片段创建视图时调用
                onActivityCreated():在活动的onCreate()方法已经返回时调用
                onDestroyView():与片段关联的视图被移除时调用
                onDetach():取消片段与活动的关联时调用。












    推荐阅读