本篇大致总结下DialogFragment的概述、简单使用和部分源码内容解析。
DialogFragment概述
DialogFragment是一种特殊的Fragment,用于显示对话框,提供了一种方便的方式来管理对话框的生命周期,并与Activity的生命周期进行集成。相比更早的Dialog,AlertDialog有一个很大的缺点就是不受Activity/Fragment生命周期的管理,很容易出现Crash,而且屏幕切换以后还不能自动保留状态等,所以Android提供了另一个DialogFragment专门来解决这些问题,而且Google和阿里Android开发手册中都推荐使用DialogFrgament。
DialogFragment简单使用
- 创建MyDialogFragment继承自DialogFragment
public class MyDialogFragment extends DialogFragment {
@Override
public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_layout, container, false);
initView(view);
return view;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
// 点击外部区域是否dismiss dialog
dialog.setCanceledOnTouchOutside(false);
// 设置背景
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.GREEN));
return dialog;
}
@Override
public void onStart() {
super.onStart();
Window window = getDialog().getWindow();
// 设置dialog宽高
window.setLayout(500, 300);
// 设置dialog显示位置
window.setGravity(Gravity.CENTER);
}
private void initView(View view){
view.findViewById(R.id.dismiss_btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
}
}
- 创建Dialog布局
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="50sp"
android:text="测试弹窗"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
<Button
android:id="@+id/dismiss_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="dismiss"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
- 在MainActivity中创建MyDialogFragment实例使用
private void initView(){
findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MyDialogFragment dialog = new MyDialogFragment();
dialog.show(getSupportFragmentManager(), "test_dialog");
}
});
}
DialogFragment源码解析
DialogFragment是Dialog和Fragment功能的结合,保留了Fragment与Activity生命周期一致的特性,在横竖屏切换的时候,Activity经历销毁和重新创建,如果是Dialog,在屏幕状态切换之后弹窗就会消失,而DialogFragment会随Activity生命周期同样经历销毁和重新创建的过程,并保持销毁前的状态。
- DialogFragment中有状态保存机制savedInstanceState,用来保存弹窗状态。
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
if (mDialog != null) {
Bundle dialogState = mDialog.onSaveInstanceState();
if (dialogState != null) {
outState.putBundle(SAVED_DIALOG_STATE_TAG, dialogState);
}
}
if (mStyle != STYLE_NORMAL) {
outState.putInt(SAVED_STYLE, mStyle);
}
if (mTheme != 0) {
outState.putInt(SAVED_THEME, mTheme);
}
if (!mCancelable) {
outState.putBoolean(SAVED_CANCELABLE, mCancelable);
}
if (!mShowsDialog) {
outState.putBoolean(SAVED_SHOWS_DIALOG, mShowsDialog);
}
if (mBackStackId != -1) {
outState.putInt(SAVED_BACK_STACK_ID, mBackStackId);
}
}
在DialogFragment每次创建的时候都会先判断是否有已经保存的状态数据,如果有的话取出,这样重新创建之后的弹窗就与销毁之前的保持一致,给用户的感觉就好像弹窗没销毁过一样。
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// This assumes that onCreate() is being called on the main thread
mHandler = new Handler();
mShowsDialog = mContainerId == 0;
if (savedInstanceState != null) {
mStyle = savedInstanceState.getInt(SAVED_STYLE, STYLE_NORMAL);
mTheme = savedInstanceState.getInt(SAVED_THEME, 0);
mCancelable = savedInstanceState.getBoolean(SAVED_CANCELABLE, true);
mShowsDialog = savedInstanceState.getBoolean(SAVED_SHOWS_DIALOG, mShowsDialog);
mBackStackId = savedInstanceState.getInt(SAVED_BACK_STACK_ID, -1);
}
}
- DialogFragment中的onCreateDialog()是DialogFragment的一个回调方法,用于创建对话框示例,如果onCreateDialog()和onCreateView()中都写了布局,会优先使用OnCreateDialog()中的布局,如果onCreateDialog()不重写,DialogFragment会自动创建一个空白的dialog,布局则使用onCreateView中的布局。
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
return new Dialog(requireContext(), getTheme());
}
- DialogFragment的生命周期其实就是随着Fragment的生命周期执行的,DialogFragment会重写Fragment中的生命周期来管理Dialog。
@Override
public void onStart() {
super.onStart();
// mDialog的来源:mDialog = onCreateDialog(savedInstanceState);
if (mDialog != null) {
mViewDestroyed = false;
mDialog.show();
}
}
@Override
public void onStop() {
super.onStop();
if (mDialog != null) {
mDialog.hide();
}
}
/**
* Remove dialog.
*/
@Override
public void onDestroyView() {
super.onDestroyView();
if (mDialog != null) {
// Set removed here because this dismissal is just to hide
// the dialog -- we don't want this to cause the fragment to
// actually be removed.
mViewDestroyed = true;
// Instead of waiting for a posted onDismiss(), null out
// the listener and call onDismiss() manually to ensure
// that the callback happens before onDestroy()
mDialog.setOnDismissListener(null);
mDialog.dismiss();
if (!mDismissed) {
// Don't send a second onDismiss() callback if we've already
// dismissed the dialog manually in dismissInternal()
onDismiss(mDialog);
}
mDialog = null;
}
}
DialogFragment里面的Dialog在onCreate之后创建,在onStart中展示,在onDestroyView中关闭