Android BottomSheetDialogFragment — 圆角和自定义动画

效果

实现效果

圆角

drawable
  • res/drawable/dialog_background.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <corners
        android:topLeftRadius="6dp"
        android:topRightRadius="6dp" />
    <solid android:color="#FFFFFF" />

</shape>
style
  • res/values/style.xml
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">

        ...

        <item name="bottomSheetDialogTheme">@style/AppBottomSheetDialogTheme</item>

        ...
    </style>

    <!-- 主题设置   -->
    <style name="AppBottomSheetDialogTheme" parent="Theme.MaterialComponents.Light.BottomSheetDialog">
        <item name="bottomSheetStyle">@style/AppModalStyle</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    </style>

    <!--  背景设置  -->
    <style name="AppModalStyle" parent="Widget.Design.BottomSheet.Modal">
        <item name="android:background">@drawable/dialog_background</item>
    </style>
</resources>
  • PS: 如果布局添加了android:background 属性,请去掉。
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorBg">
    <!-- 不要添加 android:background-->

    ...
    ...

</androidx.constraintlayout.widget.ConstraintLayout>

自定义动画

anim
  • res/anim/slide_up.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="@integer/fragment_anim">

    <translate
        android:fromYDelta="80%p"
        android:interpolator="@android:anim/decelerate_interpolator"
        android:toYDelta="0" />
</set>
  • res/anim/slide_down.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="@integer/fragment_anim">

    <translate
        android:fromYDelta="0"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:toYDelta="80%p" />
</set>
style
  • res/values/style.xml
<!-- 自定义弹出/关闭动画   -->
<style name="DialogAnimation">
    <item name="android:windowEnterAnimation">@anim/slide_up</item>
    <item name="android:windowExitAnimation">@anim/slide_down</item>
</style>
基类
open class CommonBasicDialogFragment : BottomSheetDialogFragment() {

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        // 设置动画
        dialog?.window?.attributes?.windowAnimations = R.style.DialogAnimation
    }
}
使用
  • 继承基类 CommonBasicDialogFragment 即可
class MyFragment() :CommonBasicDialogFragment(){
    ...
}