由于本人英文能力实在有限,不足之初敬请谅解
本博客只要没有注明“转”,那么均为原创,转贴请注明链接
本系列并没有对原文100%翻译,也没有100%的贴出原文
与Activity通信
尽管Fragment已经作为一个依赖Activity的object实现,并且可以在多个activitiy内部使用,一个已知的fragment实例是直接与包含它的activity绑定的。
特别的,这个fragment可以通过getActivity()访问Activity实例,并且轻松的执行如在activity布局中查找view一类的任务
View listView = getActivity().findViewById(R.id.list);
同样的,你的activity可以通过使用indFragmentById()或者findFragmentByTag()从FragmentManager获得一个fragment引用从而调用fragment中的方法
ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
建立activity的事件回调
In some cases, you might need a fragment to share events with the activity. A good way to do that is to define a callback interface inside the fragment and require that the host activity implement it. When the activity receives a callback through the interface, it can share the information with other fragments in the layout as necessary.
一些情况下,你也许需要一个fragment来与activity共享events。一个好的方式是在fragment内部定义一个回调接口并且要求宿主activity实现它。当activity通过这个接口收到一个回调时,如果需要的话他可以与其他在布局中的fragments分享信息。
For example, if a news application has two fragments in an activity—one to show a list of articles (fragment A) and another to display an article (fragment B)—then fragment A must tell the activity when a list item is selected so that it can tell fragment B to display the article. In this case, the OnArticleSelectedListener interface is declared inside fragment A:
例如:如果一个新闻应用在一个activity有两个fragment,一个用来显示文章列表(fragment A),另一个用来显示一篇文章(fragment B),那么当列表的条目被选中的时候fragment A必须告诉activity,这样才能通知fragment B来显示此文章。在这个例子中,OnArticleSelectedListener接口在fragment A内部声明
public static class FragmentA extends ListFragment {
...
// Container Activity must implement this interface
public interface OnArticleSelectedListener {
public void onArticleSelected(Uri articleUri);
}
...
}
fragment的宿主activity实现OnArticleSelectedListener接口并且覆盖onArticleSelected()用来通知fragment B来自fragment A的事件。
为了保证宿主activity实现这个接口,fragment A的onAttach()回调方法(当往activity添加activity时由系统调用)通过强制转换传入onAttach()方法的Activity,实例化一个OnArticleSelectedListener实例。
public static class FragmentA extends ListFragment {
OnArticleSelectedListener mListener;
...
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnArticleSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener");
}
}
...
}
如果activity没有实现这个接口,那么fragment会抛出ClassCastException异常。如果成功,mListener成员变量会持有一个实现了OnArticleSelectedListener接口的activity引用,那么fragment A可以通过activity中调用OnArticleSelectedListener接口定义好的方法来分享event。例如:如果fragment A是ListFragment的一个扩展,每次用户点击列表条目的时候,系统调用fragment的onListItemClick()方法,其中fragment调用onArticleSelected()来与activity分享event
public static class FragmentA extends ListFragment {
OnArticleSelectedListener mListener;
...
@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);
}
...
}
向Action Bar添加条目
你的fragment可以贡献menu条目到activity的Options Menu通过实现onCreateOptionsMenu()。为了让这个方法可以接收到调用,无论怎样,在onCreate()期间,你必须调用setHasOptionsMenu()来告诉fragment愿意为Options Menu添加条目(否则,fragment不会收到onCreateOptionsMenu()的调用)
Any items that you then add to the Options Menu from the fragment are appended to the existing menu items. The fragment also receives callbacks to onOptionsItemSelected() when a menu item is selected.
任何从fragment追加到已经存在的menu条目上的条目添加到Options Menu中。当一个menu条目被选中时fragment也会收到onOptionsItemSelected()的回调
你也可以在你的fragment布局中注册一个view通过调用registerForContextMenu()用来提供一个context menu。当用户打开context menu时,fragment会收到一个onCreateContextMenu()调用。当用户选中一个条目时,fragment会收到一个onContextItemSelected()的调用。
Note: Although your fragment receives an on-item-selected callback for each menu item it adds, the activity is first to receive the respective callback when the user selects a menu item. If the activity's implementation of the on-item-selected callback does not handle the selected item, then the event is passed to the fragment's callback. This is true for the Options Menu and context menus.
注意:尽管fragment的每一个添加的menu条目都会收到一个on-item-selected回调,但activity会首先获得相应的回调。如果activity中on-item-selected回调的实现没有处理选中的item,那么event会传递给fragment的回调。对于Options Menu和context menus都是如此。
处理Fragment声明周期
管理fragment的声明周期与管理activity的声明周期很像。和activity一样,fragment可以存在于3中状态:
Resumed
fragment在运行中的activity可见
Paused
另一个activity运行并聚焦在前台,但是含有fragment的activity仍然是可见的(在上面的activity是部分透明的或者他没有覆盖整个屏幕)。
Stopped
The fragment is not visible. Either the host activity has been stopped or the fragment has been removed from the activity but added to the back stack. A stopped fragment is still alive (all state and member information is retained by the system). However, it is no longer visible to the user and will be killed if the activity is killed.
Also like an activity, you can retain the state of a fragment using a Bundle, in case the activity's process is killed and you need to restore the fragment state when the activity is recreated. You can save the state during the fragment's onSaveInstanceState() callback and restore it during either onCreate(), onCreateView(), or onActivityCreated().
fragment是不可见的。宿主activity被stopped,或者fragment被从activity中remove掉但是添加到了back stack中。一个stopped的fragment仍然处于活着的状态(所有的状态和成员信息被系统保存着)。不管怎样,它对用户来说不再可见,并且activity被killed的时候fragment也随之被kill掉。和activity一样,你可以用Bundle保存fragment的状态,万一activity的进程被kill掉并且当activity重新create的时候你需要恢复fragment的状态。你可以在fragment的onSaveInstanceState()调用期间保存状态,在onCreate()、onCreateView()或onActivityCreated()期间恢复其状态。
The most significant difference in lifecycle between an activity and a fragment is how one is stored in its respective back stack. An activity is placed into a back stack of activities that's managed by the system when it's stopped, by default (so that the user can navigate back to it with the Back button, as discussed in Tasks and Back Stack). However, a fragment is placed into a back stack managed by the host activity only when you explicitly request that the instance be saved by calling addToBackStack() during a transaction that removes the fragment.
activity与fragment的声明周期最重要的区别是如何保存到他们各自的back stack中。当activity stopped的时候,它放置到由系统管理的activities的back stack中,默认地(所以用户可以通过back按键导航回去,如Tasks and Back Stack 中讨论的一样)。仅当你明确的要求在移除fragment的事务期间,通过调用addToBackStack()保存这个fragment实例时,fragment才会被放置到一个有宿主activity管理的back stack中。
Otherwise, managing the fragment lifecycle is very similar to managing the activity lifecycle. So, the same practices for managing the activity lifecycle also apply to fragments. What you also need to understand, though, is how the life of the activity affects the life of the fragment.
其他方面,管理fragment的声明周期与管理activity的声明周期十分相似。所以与管理activity声明周期相同的练习也适用于fragments。你需要理解的是:activity的生命如何影响到fragment的生命
Coordinating with the activity lifecycle
与activity生命周期的协调
The lifecycle of the activity in which the fragment lives directly affects the lifecycle of the fragment, such that each lifecycle callback for the activity results in a similar callback for each fragment. For example, when the activity receives onPause(), each fragment in the activity receives onPause().
fragment宿主activity的声明周期直接影响到fragment生命周期,以至于对每一个fragment,activity每一个生命周期的回调导致一个相似的回调。例如:当activity收到onPause()时,activity中的每一个fragment也会收到onPause()
Fragments have a few extra lifecycle callbacks, however, that handle unique interaction with the activity in order to perform actions such as build and destroy the fragment's UI. These additional callback methods are:
Fragments有一些附加的生命周期回调,他们处理独有的与activity的交互,为了执行如建立和销毁fragment的UI一类的action。这些附件的回调方法有:
onAttach()
Called when the fragment has been associated with the activity (the Activity is passed in here).
onCreateView()
Called to create the view hierarchy associated with the fragment.
onActivityCreated()
Called when the activity's onCreate() method has returned.
onDestroyView()
Called when the view hierarchy associated with the fragment is being removed.
onDetach()
Called when the fragment is being disassociated from the activity.
you can see how each successive state of the activity determines which callback methods a fragment may receive. For example, when the activity has received its onCreate() callback, a fragment in the activity receives no more than the onActivityCreated() callback.
可以看到每一个activity依次的状态如何决定fragment会收到哪一个函数的回调。
当activity收到他的onCreate()回调时,activity中的fragmet至多会收到onActivityCreated()的回调
Once the activity reaches the resumed state, you can freely add and remove fragments to the activity. Thus, only while the activity is in the resumed state can the lifecycle of a fragment change independently.
一旦activit到了resumed状态,你可以随意在activity中的添加和删除fragment。仅当这个activity是处于resumed状态下fragment的生命周期才可以独立的改变。
However, when the activity leaves the resumed state, the fragment again is pushed through its lifecycle by the activity.
无论怎样,当activity离开resumed状态时,fragment又一次被activity挤入它的下一个生命周期。
原文地址如下,英文水平实在有限,希望拍砖同时能给予指正。
http://developer.android.com/guide/topics/fundamentals/fragments.html
转贴请保留以下链接
本人blog地址