DialogFragment生命週期簡介
之前一篇文章Dialog使用介紹介紹了DialogFragemnt的一些使用常識,本文來簡單介紹DialogFragment常用的生命週期函數,調用順序如下:
onAttach -->onCreate–>onCreateDialog–>onCreateView–>onViewCreated–>onSaveInstanceState
在onAttach裏傳入要attach的Activity實例,使得在DialogFragment中可以調用Activity的函數。
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
historyViewClickListener = (OnHistoryViewClickListener) activity;
context = activity;
}
在onCreate裏對DialogFragment的樣式進行設置,如是不是全屏顯示,要不要展示Titlebar等。
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(STYLE_NO_FRAME, android.R.style.Theme_Holo_Light); // 沒有titlebar,全屏展示
}
在onCreateDialog裏設置dialog監聽函數,如對返回鍵的監聽。
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
doHide();
return true;
}
return false;
}
});
return dialog;
}
在onCreateView中進行view的初始化,並且解析savedIsntanceState Bundle數據,處理DialogFragment被回收後進行重建的數據處理邏輯。
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = getActivity().getLayoutInflater().inflate(R.layout.atom_flight_history_record_view, container, false);
Injector.inject(this, view);
if (null != savedInstanceState) {
records = (List<SearchRecord>) savedInstanceState.getSerializable("records");
isShowDays = savedInstanceState.getBoolean("isShowDays", false);
spaceHeight = savedInstanceState.getInt("spaceHeight");
listAdapter = new FlightHistoryListAdapter(context, records, isShowDays);
} else {
listAdapter = new FlightHistoryListAdapter(context, records, isShowDays);
}
return view;
}
onViewCreated緊跟在onCreateView之後執行,執行界面初始化完成之後的一些操作,如動畫效果。
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
showHistoryAnimation();
}
在onSaveInstanceState中保存重構頁面需要的數據。
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("records", (Serializable) records);
outState.putBoolean("isShowDays", isShowDays);
outState.putInt("spaceHeight", spaceHeight);
}