美文网首页
android BottomSheetDialogFragmen

android BottomSheetDialogFragmen

作者: JayQiu | 来源:发表于2022-07-25 18:18 被阅读0次

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

  <style name="Theme.Design.Light.BottomSheetDialog" parent="Theme.AppCompat.Light.Dialog">
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowAnimationStyle">@style/Animation.Design.BottomSheetDialog</item>
    <item name="bottomSheetStyle">@style/Widget.Design.BottomSheet.Modal</item>
  </style>

<style name="Widget.Design.BottomSheet.Modal" parent="android:Widget">
    <item name="enforceMaterialTheme">false</item>
    <item name="android:background">?android:attr/colorBackground</item>
    <item name="android:elevation" ns1:ignore="NewApi">
      @dimen/design_bottom_sheet_modal_elevation
    </item>
    <item name="behavior_peekHeight">auto</item>
    <item name="behavior_hideable">true</item>
    <item name="behavior_skipCollapsed">false</item>
    <item name="shapeAppearance">@null</item>
    <item name="shapeAppearanceOverlay">@null</item>
    <item name="backgroundTint">?android:attr/colorBackground</item>
  </style>

设置圆角和背景

 <!--BottomSheetDialog弹窗,圆角没问题-->
    <style name="BottomSheetDialog" parent="Theme.Design.Light.BottomSheetDialog">
        <item name="enableEdgeToEdge">true</item>
        <item name="bottomSheetStyle">@style/bottomSheetStyleWrapper</item>
        <item name="android:backgroundDimEnabled">false</item>
    </style>

    <style name="bottomSheetStyleWrapper" parent="Widget.Design.BottomSheet.Modal">
        <item name="android:background">@android:color/transparent</item>
    </style>

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

design_bottom_sheet_dialog 源码

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

  <androidx.coordinatorlayout.widget.CoordinatorLayout
      android:id="@+id/coordinator"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:fitsSystemWindows="true">

    <View
        android:id="@+id/touch_outside"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:focusable="false"
        android:importantForAccessibility="no"
        android:soundEffectsEnabled="false"
        tools:ignore="UnusedAttribute"/>

    <FrameLayout
        android:id="@+id/design_bottom_sheet"
        style="?attr/bottomSheetStyle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal|top"
        app:layout_behavior="@string/bottom_sheet_behavior"/>

  </androidx.coordinatorlayout.widget.CoordinatorLayout>

</FrameLayout>

在 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 BottomSheetDialogFragmen

      本文链接:https://www.haomeiwen.com/subject/dajgirtx.html