參考:http://www.rzrgm.cn/qlky/p/7210403.html
https://blog.csdn.net/shixianzuishuai/article/details/140906330
創(chuàng)建Fragment與創(chuàng)建Activity類似,開發(fā)者實(shí)現(xiàn)的Fragment必須繼承Fragment基類。Android 9將原來的Fragment等基類都標(biāo)記為過時(shí),推薦使用support fragment下的Fragment,升級(jí)后的Fragment具有更好的適用性。
Android提供了如下的Fragment繼承體系:開發(fā)者實(shí)現(xiàn)的Fragment可以根據(jù)需要繼承上述Fragment基類或其任意子類。
實(shí)現(xiàn)Fragment與實(shí)現(xiàn)Activity非常相似,需要實(shí)現(xiàn)與Activity類似的回調(diào)方法,如onCreate()、onCreateView()、onStart()、onResume()、onPause()、onStop()等。
通常來說,創(chuàng)建Fragment需要實(shí)現(xiàn)如下三個(gè)方法:
onCreate(): 系統(tǒng)創(chuàng)建Fragment對(duì)象后回調(diào)該方法,用于初始化想要在Fragment中保持的必要組件。
onCreateView(): Fragment繪制界面組件時(shí)回調(diào)該方法,必須返回一個(gè)View,該View即為Fragment所顯示的View。
onPause(): 用戶離開Fragment時(shí)回調(diào)該方法。
為了控制Fragment顯示的組件,通常需要重寫onCreateView()方法,該方法返回的View將作為Fragment顯示的組件。
Fragment的生命周期方法包括:
onAttach(): 當(dāng)Fragment被添加到其所在的Context時(shí)回調(diào)。只會(huì)被調(diào)用一次。
onCreate(): 創(chuàng)建Fragment時(shí)回調(diào)。只會(huì)被調(diào)用一次。
onCreateView(): 每次創(chuàng)建、繪制Fragment的View組件時(shí)回調(diào)。必須返回一個(gè)View。
onActivityCreated(): 當(dāng)Fragment所在的Activity啟動(dòng)完成后回調(diào)。
onStart(): 啟動(dòng)Fragment時(shí)回調(diào)。
onResume(): 恢復(fù)Fragment時(shí)回調(diào)。在onStart()方法后一定會(huì)回調(diào)onResume()。
onPause(): 暫停Fragment時(shí)回調(diào)。
onStop(): 停止Fragment時(shí)回調(diào)。
onDestroyView(): 銷毀Fragment所包含的View組件時(shí)調(diào)用。
onDestroy(): 銷毀Fragment時(shí)回調(diào)。只會(huì)被調(diào)用一次。
onDetach(): 將Fragment從其所在的Context中刪除、替換完成時(shí)回調(diào)。在onDestroy()方法后一定會(huì)回調(diào)onDetach()方法。只會(huì)被調(diào)用一次。
示例代碼:
package com.jay.myappstudy; import android.content.Context; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.jay.common.LocalDateTimeUtil; public class FragmentTest1 extends Fragment { /** * 畫面視圖 */ private View mView; /** * 刷新按鈕 */ private Button btnRefresh; /** * 展示文本 */ private TextView txtMsg; /** * 參數(shù)1 */ private String mPara1; /** * Fragment回調(diào)函數(shù) */ private Callbacks mCallbacks; /** * 按鈕事件 */ private View.OnClickListener clickListener = new View.OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnRefresh: String nowStr = LocalDateTimeUtil.getNowString(); txtMsg.setText("當(dāng)前時(shí)間:" + nowStr); executeCallback(nowStr); break; default: txtMsg.setText("未知操作"); break; } } }; public FragmentTest1() { } /** * 構(gòu)造函數(shù)傳參 */ public FragmentTest1(String para1) { this.mPara1 = para1; } public FragmentTest1(String para1, Callbacks callback) { this.mPara1 = para1; this.mCallbacks = callback; } /** * Fragment繪制界面組件時(shí)回調(diào)該方法,必須返回一個(gè)View,該View即為Fragment所顯示的View。 */ @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { //return super.onCreateView(inflater, container, savedInstanceState); mView = inflater.inflate(R.layout.fragment_test_form1, container, false); //獲取和設(shè)置視圖中的控件 if (mView != null) { btnRefresh = mView.findViewById(R.id.btnRefresh); txtMsg = mView.findViewById(R.id.txtMsg); btnRefresh.setOnClickListener(clickListener); } return mView; } /** * 創(chuàng)建Fragment時(shí)回調(diào)。只會(huì)被調(diào)用一次。 * 系統(tǒng)創(chuàng)建Fragment對(duì)象后回調(diào)該方法,用于初始化想要在Fragment中保持的必要組件。 */ @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); //獲取啟動(dòng)Fragment時(shí)的參數(shù) String paraName = "para1"; Bundle bundle = getArguments(); if (bundle != null && bundle.containsKey(paraName)) { //獲取Bundle中保存的參數(shù),用來做后續(xù)操作,比如查詢數(shù)據(jù)庫。 String para1Value = bundle.getString(paraName); Log.i("FragmentTest", "獲取參數(shù):" + para1Value); } } /** * 當(dāng)Fragment被添加到其所在的Context時(shí)回調(diào)。只會(huì)被調(diào)用一次。 * onAttach()方法的參數(shù)是一個(gè)Context對(duì)象,表示宿主Activity的上下文。 * 通過該參數(shù),F(xiàn)ragment可以獲取到宿主Activity的引用,從而與宿主Activity進(jìn)行通信和交互。 */ @Override public void onAttach(Context context) { super.onAttach(context); //Fragment所在Activity集成實(shí)現(xiàn)回調(diào)接口函數(shù),可以通過以下方式得到回調(diào)函數(shù)對(duì)象。 // if (!(context instanceof Callbacks)) { // throw new IllegalStateException("Fragment所在的Activity必須實(shí)現(xiàn)Callbacks接口!"); // } // mCallbacks = (Callbacks) context; } /** * 執(zhí)行回調(diào)函數(shù)前可以執(zhí)行Fragment本身相關(guān)邏輯。 * */ public void executeCallback(String para) { //回調(diào)之前的處理邏輯... //回調(diào)接口 if (this.mCallbacks != null) { this.mCallbacks.onFragmentCallback(para); } } /** * 回調(diào)接口定義 */ public interface Callbacks { void onFragmentCallback(String para); } }
Fragment布局代碼
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/txtMsg" android:layout_width="match_parent" android:layout_height="20dp" android:text="點(diǎn)擊按鈕獲取當(dāng)前時(shí)間..."></TextView> <Button android:id="@+id/btnRefresh" android:layout_width="match_parent" android:layout_height="50dp" android:text="當(dāng)前時(shí)間"></Button> </LinearLayout>
Activity調(diào)用
FragmentTest1 test1 = new FragmentTest1("abc", new FragmentTest1.Callbacks() { @Override public void onFragmentCallback(String para) { Log.i("IncludeFormActivity","從Fragment中接收到的回調(diào)參數(shù):" + para); } }); //創(chuàng)建Fragment時(shí)傳參 Bundle paras = new Bundle(); paras.putString("para1","來自Activity的參數(shù)。"); test1.setArguments(paras); //加載Fragment openForm(test1);
加載和移除Fragment
/** * 刪除當(dāng)前Activity中的所有Fragment * */ private void closeAllForm(){ FragmentManager fm = ctx.getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); //刪除所有Fragment List<Fragment> fragments = fm.getFragments(); if (fragments != null) { for (Fragment fra : fragments) { ft.remove(fra); } } ft.commit(); fm.executePendingTransactions(); fragments.clear(); fm.getFragments().clear(); fragments = fm.getFragments(); if (fragments != null) { for (int i = 0; i < fragments.size(); i++) { ft.hide(fragments.get(i)); } } } /** * 加載Fragment到當(dāng)前Activity中 * */ private void openForm(Fragment fragment){ FragmentActivity act = (FragmentActivity) ctx; FragmentManager fm = ctx.getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); ft.remove(fragment); //刪除所有Fragment closeAllForm(); List<Fragment> fragments = fm.getFragments(); if (fragments != null) { for (int i = 0; i < fragments.size(); i++) { ft.hide(fragments.get(i)); } } //Add Fragment 到容器中,可以是RelativeLayout或FrameLayout等容器。 ft.add(R.id.mainContentArea, fragment); ft.show(fragment); ft.commit(); fm.executePendingTransactions(); }
Activity畫面布局
<!-- 方式1:直接引入一個(gè)Fragment -->
<fragment
android:id="@+id/fmTest1"
android:name="com.jay.myappstudy.FragmentTest1"
android:layout_width="match_parent"
android:layout_height="100dp"
/>
<!-- 方式2:添加一個(gè)Layout容器,使用后臺(tái)代碼加載Fragment到這個(gè)容器中 -->
<FrameLayout
android:id="@+id/mainContentArea"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
浙公網(wǎng)安備 33010602011771號(hào)