之前一篇文章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);
}