Fragment的生命周期和Activity之間的通信以及使用
Fragment通俗來講就是碎片,不能單獨(dú)存在,意思就是說必須依附于Activity,一般來說有兩種方式把Fragment加到Activity,分為靜態(tài),動態(tài)。
靜態(tài)即為右鍵單擊,建立一個(gè)Fragment,選擇Blank,在Activity布局中直接加fragment,name屬性直接指向之前建立的Fragment,這就添加上了Fragment,這種較為簡單。
動態(tài):
我們要做的是在Activity中添加一個(gè)Fragment,F(xiàn)ragment中有兩個(gè)按鈕,當(dāng)按下按鈕時(shí)分別切換不同的Fragment,注意,切換不同的Fragment的代碼在Activity中寫。
實(shí)現(xiàn)Fragment和Activity之間的通信,步驟一般分為五步,1、在Fragment中聲明一個(gè)接口。 2、在Activity中實(shí)現(xiàn)在Fragment中聲明的接口。
3、在Fragment中聲明一個(gè)接口對象。 4、在Fragment的生命周期中onAttach方法中判斷當(dāng)前Activity是否實(shí)現(xiàn)了此Fragment中聲明的接口
5、調(diào)用Activity中實(shí)現(xiàn)的方法 (接口對象.方法名)
首先,建立一個(gè)名為OneFragment的Fragment,在右鍵單擊建立時(shí)勾選Include fragment factory methods 和Include interface callback,這樣會自動添加相關(guān)代碼,省掉很多時(shí)間.再在新建立的Fragment里添加兩個(gè)按鈕,設(shè)置Id。
布局代碼如下
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.administrator.homeworepar.Fragment.OneFragment">
<!-- TODO: Update blank fragment layout -->
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/bt1"
android:text="好友"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/bt2"
android:text="消息"
android:layout_gravity="center_horizontal|top" />
</FrameLayout>
下面為Fragment的代碼
package com.example.administrator.homeworepar.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.example.administrator.homeworepar.R;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link OneFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link OneFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class OneFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public OneFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment OneFragment.
*/
// TODO: Rename and change types and number of parameters
public static OneFragment newInstance(String param1, String param2) {
OneFragment fragment = new OneFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view=inflater.inflate(R.layout.fragment_one, container, false);
Button bt1= (Button) view.findViewById(R.id.bt1); // 實(shí)現(xiàn)的功能是的那個(gè)按下按鈕時(shí),會調(diào)用ACtivity中的changFragment方法
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mListener.changFragment(1);
}
});
Button bt2= (Button) view.findViewById(R.id.bt2);
bt2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mListener.changFragment(2);
}
});
return view;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) { 判斷是否實(shí)現(xiàn)了接口,如果實(shí)現(xiàn)了接 口,就把Activity轉(zhuǎn)換為接口的對 象,這樣就可以調(diào)用方 法
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener { // 此段為自動添加的接口,在接口中實(shí)現(xiàn)一個(gè)方法修改完后會有其他代碼出錯(cuò),只要 把出錯(cuò)代碼刪掉即可。
// TODO: Update argument type and name
void changFragment(int which);
}
再建立一個(gè)Activity,
package com.example.administrator.homeworepar.Fragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import com.example.administrator.homeworepar.R;
public class Fragment2Activity extends AppCompatActivity implements OneFragment.OnFragmentInteractionListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment2);
}
@Override
public void changFragment(int which) {
if(which==1){
Fragment fragment1=new BlankFragment(); //實(shí)現(xiàn)Fragment中的方法,當(dāng)?shù)玫降闹禐?時(shí),把BlankFragment填充 //到Id為fl2中的FrameLayout中,
getSupportFragmentManager()
.beginTransaction().replace(R.id.fl2,fragment1).commit();
}else if(which==2){
Fragment fragment2=new SecondFragment();
getSupportFragmentManager()
.beginTransaction().replace(R.id.fl2,fragment2).commit();
}
}
}
ACtivity布局代碼如下
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.administrator.homeworepar.Fragment.Fragment2Activity">
<fragment
android:layout_width="match_parent"
android:layout_height="50dp"
android:name="com.example.administrator.homeworepar.Fragment.OneFragment"
android:id="@+id/fragment3" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/fl2"
android:layout_below="@+id/fragment3">
</FrameLayout>
</RelativeLayout>
這樣就可以實(shí)現(xiàn)ACtivity與Fragment間的通信,另外Fragment還有和Activity一樣還有生命周期的問題
方法名 說明
onAttach () Fragment被附加到Activity的時(shí),調(diào)用此函數(shù),在這個(gè)方法中可以獲得宿主Activity。
onCreate () Fragment被創(chuàng)建的時(shí),調(diào)用此函數(shù)。
onCreateView () Fragment的布局加載時(shí),調(diào)用此函數(shù)。
onActivityCreated () 當(dāng)宿主Activity啟動完畢后,調(diào)用此函數(shù)。
onStart () 啟動Fragment時(shí),調(diào)用此函數(shù)。
onResume () Fragment恢復(fù)時(shí),調(diào)用此函數(shù)。
onPause () Fragment暫停時(shí),調(diào)用此函數(shù)。
onStop() Fragment停止時(shí),調(diào)用此函數(shù)。
onDestroyView() 銷毀Fragment中的View控件時(shí),調(diào)用此函數(shù)。
onDestroy() 銷毀Fragment時(shí),調(diào)用此函數(shù)。
onDetach() Fragment從Activity脫離時(shí),調(diào)用此函數(shù)



浙公網(wǎng)安備 33010602011771號