android生命周期
Today we will learn about Android Fragment Lifecycle and implement a single activity class consisting of two fragments in android application.
今天,我们将学习Android Fragment Lifecycle,并在android应用程序中实现由两个片段组成的单个活动类。
Android片段 (Android Fragment)
Fragment
class in Android is used to build dynamic User Interfaces. Fragment should be used within the Activity. A greatest advantage of fragments is that it simplifies the task of creating UI for multiple screen sizes. A activity can contain any number of fragments.
Android中的Fragment
类用于构建动态用户界面。 片段应在活动内使用。 片段的最大优点是,它简化了为多种屏幕尺寸创建UI的任务。 一个活动可以包含任意数量的片段。
An Android fragment is not by itself a subclass of View which most other UI components are. Instead, a fragment has a view inside it. It is this view which is eventually displayed inside the activity in which the fragment lives.
Android片段本身并不是大多数其他UI组件的View的子类。 相反,片段内部有一个视图。 该视图最终显示在片段所在的活动中。
Because an android fragment is not a view, adding it to an activity looks somewhat different than adding a view (e.g. TextView). A fragment is added to a ViewGroup inside the activity. The fragment’s view is displayed inside this ViewGroup.
由于android片段不是视图,因此将其添加到活动中看起来与添加视图(例如TextView)有所不同。 片段被添加到活动内部的ViewGroup中 。 片段的视图显示在此ViewGroup中。
The following diagram shows depicts what happens when a fragment is added to an activity:
下图显示了将片段添加到活动时发生的情况:
First the activity obtains a reference to the fragment. Then it gets a reference to the ViewGroup the fragment’s view will be rendered inside. Then the activity adds the fragment. The fragment then creates its view and returns it to the activity. The view is then inserted into the ViewGroup parent, and the fragment is alive.
首先,活动获得对该片段的引用。 然后,它获取对ViewGroup的引用,该片段的视图将在其中呈现。 然后,活动添加片段。 然后,该片段创建其视图并将其返回到活动。 然后将视图插入到ViewGroup父级中,并且该片段处于活动状态。
片段生命周期 (Fragment Lifecycle)
Android fragment lifecycle is illustrated in below image.
下图说明了Android片段的生命周期。
Below are the methods of fragment lifecycle.
以下是片段生命周期的方法。
onAttach()
:This method will be called first, even before onCreate(), letting us know that your fragment has been attached to an activity. You are passed the Activity that will host your fragmentonAttach()
:即使在onCreate()之前,也会首先调用此方法,让我们知道您的片段已附加到活动中。 您通过了将托管您的片段的活动onCreateView()
: The system calls this callback when it’s time for the fragment to draw its UI for the first time. To draw a UI for the fragment, a View component must be returned from this method which is the root of the fragment’s layout. We can return null if the fragment does not provide a UIonCreateView()
:当片段第一次绘制其UI时,系统调用此回调。 要为片段绘制UI,必须从此方法返回View组件,该组件是片段布局的根。 如果片段不提供UI,我们可以返回nullonViewCreated()
: This will be called after onCreateView(). This is particularly useful when inheriting the onCreateView() implementation but we need to configure the resulting views, such as with a ListFragment and when to set up an adapteronViewCreated()
:将在onCreateView()之后调用。 这在继承onCreateView()实现时特别有用,但是我们需要配置结果视图,例如使用ListFragment以及何时设置适配器onActivityCreated()
:This will be called after onCreate() and onCreateView(), to indicate that the activity’s onCreate() has completed. If there is something that’s needed to be initialised in the fragment that depends upon the activity’s onCreate() having completed its work then onActivityCreated() can be used for that initialisation workonActivityCreated()
:将在onCreate()和onCreateView()之后调用,以指示活动的onCreate()已完成。 如果需要根据活动的onCreate()完成其工作的片段中需要初始化的内容,则可以将onActivityCreated()用于该初始化工作onStart()
: The onStart() method is called once the fragment gets visibleonStart()
:一旦片段可见,就会调用onStart()方法onPause()
: The system calls this method as the first indication that the user is leaving the fragment. This is usually where you should commit any changes that should be persisted beyond the current user sessiononPause()
:系统调用此方法作为用户离开该片段的第一个指示。 通常,您应该在此处提交应保留在当前用户会话之外的任何更改。onStop()
: Fragment going to be stopped by calling onStop()onStop()
:片段将通过调用onStop()停止onDestroyView()
: It’s called before onDestroy(). This is the counterpart to onCreateView() where we set up the UI. If there are things that are needed to be cleaned up specific to the UI, then that logic can be put up in onDestroyView()onDestroyView()
:在onDestroy()之前调用。 这与设置UI的onCreateView()相对。 如果需要针对UI进行清理,则可以将该逻辑放在onDestroyView()中。onDestroy()
: onDestroy() called to do final clean up of the fragment’s state but Not guaranteed to be called by the Android platform.onDestroy()
:调用onDestroy()进行片段状态的最终清理,但不能保证由Android平台调用。onDetach()
: It’s called after onDestroy(), to notify that the fragment has been disassociated from its hosting activityonDetach()
:在onDestroy()之后调用,以通知该片段已从其托管活动中取消关联
Android片段类 (Android Fragment Classes)
Fragments were added to the Android API in Honeycomb(API 11).
片段已添加到Honeycomb(API 11)中的Android API中。
android.app.Fragment
: The base class for all fragment definitionsandroid.app.Fragment
:所有片段定义的基类android.app.FragmentManager
: The class for interacting with fragment objects inside an activityandroid.app.FragmentManager
:用于与活动内的片段对象进行交互的类android.app.FragmentTransaction
: The class for performing an atomic set of fragment operationsandroid.app.FragmentTransaction
:用于执行片段操作的原子集的类When using a compatibility package library provided by Google, the following classes are used for implementation.
使用Google提供的兼容性软件包库时,以下类用于实现。
android.support.v4.app.FragmentActivity
: The base class for all activities using compatibility-based fragment (and loader) featuresandroid.support.v4.app.FragmentActivity
:使用基于兼容性的片段(和加载程序)功能的所有活动的基类android.support.v4.app.Fragment
android.support.v4.app.Fragment
android.support.v4.app.FragmentManager
android.support.v4.app.FragmentManager
android.support.v4.app.FragmentTransaction
android.support.v4.app.FragmentTransaction
Android片段onCreateView() (Android Fragment onCreateView())
Here’s a sample fragment using onCreateView() for its implementation:
这是使用onCreateView()实现的示例片段:
public class SampleFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parentViewGroup,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_sample, parentViewGroup, false);
return rootView;
}
}
onCreateView()
method gets a LayoutInflater, a ViewGroup and a Bundle as parameters.
onCreateView()
方法获取LayoutInflater,ViewGroup和Bundle作为参数。
LayoutInflater
is an component which can create View instance based on layout XML files. As you can see, the example actually does that by calling layout.inflate()
.
LayoutInflater
是一个可以基于布局XML文件创建View实例的组件。 如您所见,该示例实际上是通过调用layout.inflate()
。
inflate()
method takes three parameters: The id of a layout XML file (inside R.layout), a parent ViewGroup into which the fragment’s View is to be inserted, and a third boolean telling whether the fragment’s View as inflated from the layout XML file should be inserted into the parent ViewGroup. In this case we’ll pass false because the View will be attached to the parent ViewGroup elsewhere, by some of the Android code we call. When you pass false as last parameter to inflate(), the parent ViewGroup is still used for layout calculations of the inflated View, so you cannot pass null as parent ViewGroup .
inflate()
方法采用三个参数:布局XML文件的ID(在R.layout内部),将片段的View插入其中的父ViewGroup,以及第三个布尔值,指示片段的View是否从布局XML扩展了文件应插入到父ViewGroup中。 在这种情况下,我们将传递false,因为View将通过我们调用的某些Android代码附加到父ViewGroup的其他位置。 当您将false作为最后一个参数传递给inflate()时,父ViewGroup仍用于膨胀View的布局计算,因此您不能将null作为父ViewGroup传递。
ViewGroup
parameter of onCreateView() is the parent ViewGroup into which the View of the fragment is to be inserted. This is a ViewGroup inside the activity that will “host” the fragment.
onCreateView()的ViewGroup
参数是要插入片段的View的父ViewGroup。 这是活动内部的ViewGroup,将“托管”片段。
Bundle
parameter of onCreateView() is a Bundle in which the fragment can save data, just like in an Activity.
onCreateView()的Bundle
参数是一个Bundle,片段可以在其中保存数据,就像在Activity中一样。
Android片段示例 (Android Fragment Example)
Android fragments example project comprises of a single activity holding two fragments: TextFragment and MenuFragment respectively.
Android片段示例项目由一个包含两个片段的单独活动组成:分别为TextFragment和MenuFragment。
Android片段示例代码 (Android Fragment Example Code)
The MainActivity
holds the two fragments TextFragment
and MenuFragment
. So lets begin with defining the fragments in the xml layout
MainActivity
包含两个片段TextFragment
和MenuFragment
。 因此,让我们开始在xml布局中定义片段
activity_main.xml
activity_main.xml
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="1.0">
<fragment
android:layout_height="match_parent"
android:layout_width="match_parent"
class="journaldev.com.fragments.fragments.MenuFragment"
android:id="@+id/fragment"
android:layout_weight="0.5"/>
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
class="journaldev.com.fragments.fragments.TextFragment"
android:id="@+id/fragment2"
android:layout_weight="0.5"/>
</LinearLayout>
As we can see the class files of the fragments that are a part of this activity are defined as class=”journaldev.com.fragments.fragments.TextFragment”
我们可以看到,作为该活动一部分的片段的类文件定义为class =“ journaldev.com.fragments.fragments.TextFragment”
The fragment classes and their layouts are defined as shown in the snippets below.
片段类及其布局的定义如下面的代码片段所示。
package journaldev.com.fragments.fragments;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import journaldev.com.fragments.R;
public class TextFragment extends Fragment {
TextView text,vers;
@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.text_fragment, container, false);
text= (TextView) view.findViewById(R.id.AndroidOs);
vers= (TextView)view.findViewById(R.id.Version);
return view;
}
public void change(String txt, String txt1){
text.setText(txt);
vers.setText(txt1);
}
}
text_fragment.xml
text_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:gravity="center"
android:background="#5ba4e5"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="40px"
android:textColor="#ffffff"
android:layout_gravity="center"
android:id="@+id/AndroidOs"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#ffffff"
android:textSize="30px"
android:id="@+id/Version"/>
</LinearLayout>
The TextFragment comprises of textviews holding the android version name and number.
TextFragment由保存Android版本名称和编号的文本视图组成。
package journaldev.com.fragments.fragments;
import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import journaldev.com.fragments.R;
public class MenuFragment extends ListFragment {
String[] AndroidOS = new String[] { "Cupcake","Donut","Eclair","Froyo","Gingerbread","Honeycomb","Ice Cream SandWich","Jelly Bean","KitKat" };
String[] Version = new String[]{"1.5","1.6","2.0-2.1","2.2","2.3","3.0-3.2","4.0","4.1-4.3","4.4"};
@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.list_fragment, container, false);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, AndroidOS);
setListAdapter(adapter);
return view;
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
TextFragment txt = (TextFragment)getFragmentManager().findFragmentById(R.id.fragment2);
txt.change(AndroidOS[position],"Version : "+Version[position]);
getListView().setSelector(android.R.color.holo_blue_dark);
}
}
list_fragment.xml
list_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@android:id/list" />
</LinearLayout>
The MenuFragment displays a ListView. As we can see here, the layout of ListView is default simple_list_item_1 opposed to the custom layout we created for the ListView in the previous article.
MenuFragment显示一个ListView。 正如我们在这里看到的,ListView的布局是默认的simple_list_item_1,与我们在上一篇文章中为ListView创建的自定义布局相反。
The MainActivity invokes the setContentView from the onCreate Method, that’s it. The fragments are called from the xml file.
MainActivity从onCreate方法调用setContentView就是这样。 这些片段是从xml文件中调用的。
Alternatively we can add the fragments from the activity class using FragmentManager
as shown in the snippet below:
或者,我们可以使用FragmentManager
来添加来自活动类的FragmentManager
,如下面的代码片段所示:
getFragmentManager()
.beginTransaction()
.add(R.id.fragmentParentViewGroup, new MyFragment())
.commit();
Here the id fragmentParentViewGroup belongs to the FrameLayout shown below:
这里的ID fragmentParentViewGroup属于以下所示的的FrameLayout:
<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:id="@+id/fragmentParentViewGroup"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MyActivity"
tools:ignore="MergeRootFrame" />
Android片段示例应用 (Android Fragment Example App)
Below shows the output produced by our project, you can see that two fragments are present here and when you select any one of them in the left side fragment, data gets populated in the right side fragment.
下面显示了我们的项目产生的输出,您可以看到此处存在两个片段,并且当您在左侧片段中选择其中一个时,数据将填充在右侧片段中。
You can download final android fragment project from below link.
您可以从下面的链接下载最终的android片段项目 。
翻译自: https://www.journaldev.com/9266/android-fragment-lifecycle
android生命周期