android BottomSheetDialogFragment 详解

Android BottomSheetDialogFragment 是在com.google.android.material 中

BottomSheetDialogFragment 是继承AppCompatDialogFragment,AppCompatDialogFragment 继承DialogFragment,最后DialogFragment 继承的 Fragment
既然BottomSheetDialogFragment 最后继承的Fragment 显然他也是有自己的生命周期的。

BottomSheetDialogFragment 源码分析

//官方翻译
//Modal bottom sheet. This is a version of androidx.fragment.app.DialogFragment that shows a bottom sheet using BottomSheetDialog instead of a floating dialog.
//模态底板。这是androidx.fragment.app.DialogFragment的一个版本,它使用BottomSheetDialog而不是浮动对话框而是显示底部工作表。
public class BottomSheetDialogFragment extends AppCompatDialogFragment {
  @NonNull
  @Override
  public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
    return new BottomSheetDialog(getContext(), getTheme());
  }

明显的看出 BottomSheetDialogFragment在重写onCreateDialog 中 new BottomSheetDialog

BottomSheetDialog 源码


  public BottomSheetDialog(@NonNull Context context) {
    this(context, 0);
    ....
  }

  public BottomSheetDialog(@NonNull Context context, @StyleRes int theme) {
    super(context, getThemeResId(context, theme));
}

  private static int getThemeResId(@NonNull Context context, int themeId) {
    if (themeId == 0) {
      // If the provided theme is 0, then retrieve the dialogTheme from our theme
      TypedValue outValue = new TypedValue();
      if (context.getTheme().resolveAttribute(R.attr.bottomSheetDialogTheme, outValue, true)) {
        themeId = outValue.resourceId;
      } else {
        // bottomSheetDialogTheme is not provided; we default to our light theme
        themeId = R.style.Theme_Design_Light_BottomSheetDialog;
      }
    }
    return themeId;
  }

  @Override
  public void setContentView(@LayoutRes int layoutResId) {
    super.setContentView(wrapInBottomSheet(layoutResId, null, null));
  }
  @Override
  public void setContentView(View view) {
    super.setContentView(wrapInBottomSheet(0, view, null));
  }

  @Override
  public void setContentView(View view, ViewGroup.LayoutParams params) {
    super.setContentView(wrapInBottomSheet(0, view, params));
  }


private View wrapInBottomSheet(
      int layoutResId, @Nullable View view, @Nullable ViewGroup.LayoutParams params) {
    ensureContainerAndBehavior();
    CoordinatorLayout coordinator = (CoordinatorLayout) container.findViewById(R.id.coordinator);
    if (layoutResId != 0 && view == null) {
      view = getLayoutInflater().inflate(layoutResId, coordinator, false);
    }

    if (edgeToEdgeEnabled) {
      ViewCompat.setOnApplyWindowInsetsListener(
          bottomSheet,
          new OnApplyWindowInsetsListener() {
            @Override
            public WindowInsetsCompat onApplyWindowInsets(View view, WindowInsetsCompat insets) {
              if (edgeToEdgeCallback != null) {
                behavior.removeBottomSheetCallback(edgeToEdgeCallback);
              }

              if (insets != null) {
                edgeToEdgeCallback = new EdgeToEdgeCallback(bottomSheet, insets);
                behavior.addBottomSheetCallback(edgeToEdgeCallback);
              }

              return insets;
            }
          });
    }

    bottomSheet.removeAllViews();
    if (params == null) {
      bottomSheet.addView(view);
    } else {
      bottomSheet.addView(view, params);
    }
    // We treat the CoordinatorLayout as outside the dialog though it is technically inside
    coordinator
        .findViewById(R.id.touch_outside)
        .setOnClickListener(
            new View.OnClickListener() {
              @Override
              public void onClick(View view) {
                if (cancelable && isShowing() && shouldWindowCloseOnTouchOutside()) {
                  cancel();
                }
              }
            });
    // Handle accessibility events
    ViewCompat.setAccessibilityDelegate(
        bottomSheet,
        new AccessibilityDelegateCompat() {
          @Override
          public void onInitializeAccessibilityNodeInfo(
              View host, @NonNull AccessibilityNodeInfoCompat info) {
            super.onInitializeAccessibilityNodeInfo(host, info);
            if (cancelable) {
              info.addAction(AccessibilityNodeInfoCompat.ACTION_DISMISS);
              info.setDismissable(true);
            } else {
              info.setDismissable(false);
            }
          }

          @Override
          public boolean performAccessibilityAction(View host, int action, Bundle args) {
            if (action == AccessibilityNodeInfoCompat.ACTION_DISMISS && cancelable) {
              cancel();
              return true;
            }
            return super.performAccessibilityAction(host, action, args);
          }
        });
    bottomSheet.setOnTouchListener(
        new View.OnTouchListener() {
          @Override
          public boolean onTouch(View view, MotionEvent event) {
            // Consume the event and prevent it from falling through
            return true;
          }
        });
    return container;
  }

  /** Creates the container layout which must exist to find the behavior */
  private FrameLayout ensureContainerAndBehavior() {
    if (container == null) {
      container =
          (FrameLayout) View.inflate(getContext(), R.layout.design_bottom_sheet_dialog, null);

      coordinator = (CoordinatorLayout) container.findViewById(R.id.coordinator);
      bottomSheet = (FrameLayout) container.findViewById(R.id.design_bottom_sheet);

      behavior = BottomSheetBehavior.from(bottomSheet);
      behavior.addBottomSheetCallback(bottomSheetCallback);
      behavior.setHideable(cancelable);
    }
    return container;
  }

通过BottomSheetBehavior.from(bottomSheet);获取到BottomSheetBehavior,外部可以使用getBehavior()获取到behavior
Style 是在getThemeResId 中默认Theme_Design_Light_BottomSheetDialog
如果我们需要自定义样式BottomSheetDialog 传入你定义的Style

  


设置圆角和背景

 
    

    

我们还发现不局是在setContentView 中进行装载的

design_bottom_sheet_dialog 源码



  

    

    

  


在 design_bottom_sheet 中有一个bottomSheetStyle 对底部的FrameLayout 设置Style,
也可以看出我们可以设置design_bottom_sheet 的高度从而设置BottomSheetDialogFragment的固定高度

override fun onStart() {
        super.onStart()
        dialog?.window?.setDimAmount(0f) //设置布局
       val h = (0.85 * resources.displayMetrics.heightPixels).toInt()
        val viewRoot: FrameLayout =
            dialog?.findViewById(com.google.android.material.R.id.design_bottom_sheet)!!
        viewRoot.apply {
            layoutParams.width = -1
            layoutParams.height = h
        }
}

val mDialogBehavior = BottomSheetBehavior.from(view?.parent as View) //dialog的高度
mDialogBehavior.peekHeight = h

透明Dialog设置

 override fun onStart() {
        super.onStart()
dialog?.window?.setDimAmount(0f)// 设置透明度
}

你可能感兴趣的:(android BottomSheetDialogFragment 详解)