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.
//模態(tài)底板。這是androidx.fragment.app.DialogFragment的一個(gè)版本特愿,它使用BottomSheetDialog而不是浮動(dòng)對(duì)話框而是顯示底部工作表刺桃。
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 中默認(rèn)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>

設(shè)置圓角和背景

 <!--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>

我們還發(fā)現(xiàn)不局是在setContentView 中進(jìn)行裝載的

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 中有一個(gè)bottomSheetStyle 對(duì)底部的FrameLayout 設(shè)置Style皇筛,
也可以看出我們可以設(shè)置design_bottom_sheet 的高度從而設(shè)置BottomSheetDialogFragment的固定高度

override fun onStart() {
        super.onStart()
        dialog?.window?.setDimAmount(0f) //設(shè)置布局
       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設(shè)置

 override fun onStart() {
        super.onStart()
dialog?.window?.setDimAmount(0f)// 設(shè)置透明度
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市坠七,隨后出現(xiàn)的幾起案子水醋,更是在濱河造成了極大的恐慌,老刑警劉巖彪置,帶你破解...
    沈念sama閱讀 221,635評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件拄踪,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡拳魁,警方通過查閱死者的電腦和手機(jī)惶桐,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,543評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來潘懊,“玉大人姚糊,你說我怎么就攤上這事∈谥郏” “怎么了救恨?”我有些...
    開封第一講書人閱讀 168,083評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長释树。 經(jīng)常有香客問我忿薇,道長裙椭,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,640評(píng)論 1 296
  • 正文 為了忘掉前任署浩,我火速辦了婚禮揉燃,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘筋栋。我一直安慰自己炊汤,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,640評(píng)論 6 397
  • 文/花漫 我一把揭開白布弊攘。 她就那樣靜靜地躺著抢腐,像睡著了一般。 火紅的嫁衣襯著肌膚如雪襟交。 梳的紋絲不亂的頭發(fā)上迈倍,一...
    開封第一講書人閱讀 52,262評(píng)論 1 308
  • 那天,我揣著相機(jī)與錄音捣域,去河邊找鬼啼染。 笑死,一個(gè)胖子當(dāng)著我的面吹牛焕梅,可吹牛的內(nèi)容都是我干的迹鹅。 我是一名探鬼主播,決...
    沈念sama閱讀 40,833評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼贞言,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼斜棚!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起该窗,我...
    開封第一講書人閱讀 39,736評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤弟蚀,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后酗失,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體粗梭,經(jīng)...
    沈念sama閱讀 46,280評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,369評(píng)論 3 340
  • 正文 我和宋清朗相戀三年级零,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了断医。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,503評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡奏纪,死狀恐怖鉴嗤,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情序调,我是刑警寧澤醉锅,帶...
    沈念sama閱讀 36,185評(píng)論 5 350
  • 正文 年R本政府宣布,位于F島的核電站发绢,受9級(jí)特大地震影響硬耍,放射性物質(zhì)發(fā)生泄漏垄琐。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,870評(píng)論 3 333
  • 文/蒙蒙 一经柴、第九天 我趴在偏房一處隱蔽的房頂上張望狸窘。 院中可真熱鬧,春花似錦坯认、人聲如沸翻擒。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,340評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽陋气。三九已至,卻和暖如春引润,著一層夾襖步出監(jiān)牢的瞬間巩趁,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,460評(píng)論 1 272
  • 我被黑心中介騙來泰國打工淳附, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留议慰,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,909評(píng)論 3 376
  • 正文 我出身青樓燃观,卻偏偏與公主長得像褒脯,于是被迫代替她去往敵國和親便瑟。 傳聞我的和親對(duì)象是個(gè)殘疾皇子缆毁,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,512評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容

  • 本文會(huì)不定期更新,推薦watch下項(xiàng)目到涂。 如果喜歡請(qǐng)star脊框,如果覺得有紕漏請(qǐng)?zhí)峤籭ssue,如果你有更好的點(diǎn)子可...
    天之界線2010閱讀 13,548評(píng)論 10 123
  • 本文主要是依照一些實(shí)際的開發(fā)經(jīng)驗(yàn)践啄,然后浇雹,總結(jié)一些是些安卓底部彈窗的一些實(shí)現(xiàn)的方法與思路,希望可以給你帶來一些參考屿讽,...
    霧里看花六月天閱讀 17,535評(píng)論 0 22
  • 用兩張圖告訴你昭灵,為什么你的 App 會(huì)卡頓? - Android - 掘金 Cover 有什么料? 從這篇文章中你...
    hw1212閱讀 12,744評(píng)論 2 59
  • BottomSheet是design23.3推出的底部動(dòng)作條伐谈,google原生自帶的軟件就有這種效果烂完。效果圖: 我...
    AxeChen閱讀 9,300評(píng)論 4 24
  • 目錄介紹 10.0.0.1 Window是什么?如何通過WindowManager添加Window(代碼實(shí)現(xiàn))诵棵?W...
    楊充211閱讀 4,176評(píng)論 2 12