Definition

  • A Fragment represents a behavior or a potion of user interface in an Activity.
  • You can combile multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities.
  • A Fragment has its own life cycle, receives its own input events, and you can add or remove it while the activity is running. (sub activity)
  • A Fragment's lifecycle is directly affected by its host activity's lifecycle. It follows the activity's lifecycle, except for in resuming state. The fragment's transaction can be pushed into the backstack.

Two ways to add a fragment to acitvity

  • Define <fragment>...</fragment> in layout file.
  • In code, add a fragment to an existing ViewGroup.

Design philosophy

  • 在3.0(API 11)出现,目的是满足动态、灵活的UI设计,避免view hierarchy的频繁变化。
  • 对于目的是复用的Fragment A,尽量避免在另一个Fragment B里操作它的生命周期(因为在另一个场景下很可能就没有B了)

Creating a fragment

在实现一个Fragment时,通常需要override以下方法

  • onCreate(),完成初始化功能
  • onCreateView(),Fragment首次绘制UI时会调用该方法,返回根View,如果Fragment不需要UI,则返回null
  • onPause(),commit changes

几种Fragment

  • DialogFragment
  • ListFragment
  • PreferenceFragment

创建Fragment的几种方法

  • 布局文件里声明
<fragment android:name="com.example.news.ArticleListFragment"
android:id="@+id/list"
       android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
  • Programmatically (in Activity)
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
SampleFragment f = new SampleFragment();
ft.add(R.id.fragment_container, f);
fm.commit();

无UI的Fragment

  • 使用 add(Fragment fragment, String tag) 进行添加
  • 无需重写 onCreateView 方法
  • 使用 findFragmentByTag 获取该Fragment

Managing Fragments

FragmentManager 的作用

  • 获取Fragment:findFragmentById(有UI),findFragmentByTag(无UI)
  • 使Fragment出栈,popBackStack(),模拟用户点击Back按钮。(用处何在?)
  • 在BackStack中增加Listener,addOnBackStackChangeListener()

Performing Fragment Transactions

使用BackStack来存储Fragment的状态

// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction(); // Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null); // Commit the transaction
transaction.commit();

在commit()前使用setTransaction()来增加动画效果

Communicating with the Activity

彼此获取引用

  • Fragment通过getActivity()来获取宿主Activity的引用
  • Activity通过getFragmentManager().findFragmentById()来获取嵌入的Fragment引用

在Fragment中实现对Activity的Callback:声明一个接口,在onAttach()时将实现该接口的Activity引用保存,在需要通知Activity时调用接口中的方法

public static class FragmentA extends ListFragment {
  private OnArticleSelectedListener mListener;
...
// Container Activity must implement this interface
public interface OnArticleSelectedListener {
public void onArticleSelected(Uri articleUri);
}
...
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnArticleSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener");
}
}
...
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Append the clicked item's row ID with the content provider Uri
Uri noteUri = ContentUris.withAppendedId(ArticleColumns.CONTENT_URI, id);
// Send the event and Uri to the host activity
mListener.onArticleSelected(noteUri);
}
...
}

Fragment可以注册Options Menu与Context Menu,从而接收到onOptionsItemSelected()等事件

Handling the Fragment Lifecycle

Fragment的生命周期与Activity类似

  • create阶段,onAttach() -> onCreate() -> onCreateView() -> onActivityCreated()
  • 最大的不同在于Activity自动入栈,而Fragment需要显式声明
  • 几个方法:onCreate(),onCreateView(),onViewCreated(),onActivityCreated()
    • public void onCreate(Bundle),完成Fragment初始化工作,在onAttach(Activity)之后、onCreateView(LayoutInflater, ViewGroup, Bundle)之前发生,与宿主Activity的onCreate()方法之间没有必然的先后关系,不可以依赖宿主Activity的变量
    • public View onCreateView(LayoutInflater, ViewGroup, Bundle),创建Fragment的布局,对于非可见的Fragment,可以不重载此方法或者返回null。发生在onCreate(Bundle)之后、onActivityCreated(Bundle)之前
    • public void onViewCreated(View, Bundle),发生在onCreateView(LayoutInflater, ViewGroup, Bundle)之后、该Fragment附加到Parent之前。This gives the subclasses a chance to initialize themselves once they know their view hierarchy has been completely created.
    • public void onActivityCreated(Bundle),发生在onCreateView(LayoutInflater, ViewGroup, Bundle)后,可以进行retrive views、restore state等动作

在宿主Activity的Resume阶段,可以自由进行Fragment的增添/删除

OTHERS

用如下方法将dp换算为padding单位

int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getActivity().getResources().getDisplayMetrics());

Fragments | Android Developer的更多相关文章

  1. [转] This Android SDK requires Android Developer Toolkit version 23.0.0 or above

    问题描述: This Android SDK requires Android Developer Toolkit version 23.0.0 or above.  Current version ...

  2. !! Android developer 最新国内镜像

    Android developer 最新国内镜像: http://wear.techbrood.com, 包含Android最新文档以及Android Wear,Android TV,Android ...

  3. This Android SDK requires Android Developer Toolkit version 23.0.0 or above

    2014-07-05 12:58 6445人阅读 评论(1) 收藏 举报 This Android SDK requires Android Developer Toolkit version 23. ...

  4. 【边做项目边学Android】小白会遇到的问题--This Android SDK requires Android Developer Toolkit version 23.0.0 or above

    问题描写叙述: 上一篇讲到解决Appcompat_V7问题要减少adt版本号,于是就换旧版本号22.3.0啊,又一次打开Eclipse.立刻弹出: This Android SDK requires ...

  5. This Android SDK requires Android Developer Toolkit version 17.0.0 or above. Current version is 10.0.0.v201102162101-104271. Please update ADT to the latest version.

    win7/xp 下面安装Android虚拟机,更新SDK后,在Eclipse preference里指向android-sdk-windows时. 出现 : This Android SDK requ ...

  6. 解决在sdk manager中更新文件后出现This Android SDK requires Android Developer Toolkit version 23.1的错误

    起因:在sdksdk manager中更新了adt及其它的支持库后,eclipse报错:This Android SDK requires Android Developer Toolkit vers ...

  7. This Android SDK requires Android Developer Toolkit version 20.0.0 or above

    本人最近在操作更新ANDROID SDK时出现类似于题目中的错误,是一启动ECLIPSE时.但是,我现在只是想恢复到原先的开发环境.于是找到本文,方法有效!!! windows 下面安装Android ...

  8. this android sdk requires android developer toolkit version

    this android sdk requires android developer toolkit version 10.0.0 or above. current version is 8.0. ...

  9. 【转】This Android SDK requires Android Developer Toolkit version 20.0.0 or above

    本人最近在操作更新ANDROID SDK时出现类似于题目中的错误,是一启动ECLIPSE时.但是,我现在只是想恢复到原先的开发环境.于是找到本文,方法有效!!! windows 下面安装Android ...

随机推荐

  1. linux ubuntu系统下,adb不是内部命令 (如何才能让adb命令可以使用)

    linux ubuntu系统下,adb不是内部命令 原文地址 linux ubuntu系统下,adb不是内部命令 解决方法: 1.sudo gedit ~/.bashrc 2.将下面的两句加到上面打开 ...

  2. php自动转换pfx到pem和cer(dem格式)到pem

    经常做银行的支付接口,私钥一般都是pfx格式(私钥用来加密生成签名发送报文),公钥是cer格式(公钥用来验证返回报文里的签名).但是php里openssl只能用pem格式,每次转换都要用openssl ...

  3. RSA加密工具包

    主要参考: http://www.blogjava.net/icewee/archive/2012/05/19/378570.html http://snowolf.iteye.com/ 基于以上代码 ...

  4. zend studio 12汉化和破解

    首先提供一个 zend studio 12汉化的百度连接地址(我的网盘里有) http://pan.baidu.com/s/1dD5x1cd 下载后解压 安装方法 Help–> Install  ...

  5. Linux下文件的压缩和解压

    tar命令 解包:tar zxvf FileName.tar 打包:tar czvf FileName.tar DirName gz命令 解压1:gunzip FileName.gz 解压2:gzip ...

  6. 黄聪:wordpress前台自定义用户,调用wp_editor上传附件提示【抱歉,出于安全的考虑,不支持此文件类型】错误。

    1.直接禁用文件类型检测,在wp-config.php文件中,添加这样一句代码define('ALLOW_UNFILTERED_UPLOADS', true); 2.在functions.php里面, ...

  7. 黄聪:wordpress如何获取当前分类页面的ID、名称、别名(slug)

    <? global $wp_query; $cat_ID = get_query_var('cat'); $category = get_category($cat_ID); echo $cat ...

  8. 使用thinkphp连接sqlserver数据库时提示“系统不支持:sqlsrv”

    习惯了使用php跟mysql组合,现在接到项目需要调用客户线下的系统软件的数据,具了解,这个软件的数据库是用sqlserver数据库也就是常说的mssql数据库了. 那么我现在需要用PHP连接sqls ...

  9. webuploader在同一个页面支持多个按钮实例

    之前在时候用到webuploader ,起初是支持单实例,后来要求支持多实例. webuploder API网址,如果不懂我说的可以去查看http://fex.baidu.com/webuploade ...

  10. ubuntu vi上下左右键无法使用?

    使用vm安装ubuntu出现vi上下左右键无法正常使用. 执行以下两句就可以了 $sudo apt-get remove vim-common    $sudo apt-get install vim