Android 底部弹框实现,推荐使用 DialogFragment 来做

项目中经常需要实现底部弹出框这样的需求,实现方式有很多种,比如:Dialog、全局Activity、PopupWindow、DialogFragment都可以达到目的。经过很多实践之后,发现使用 DialogFragment 是最优的。

DialogFragment 优点

  • 它本身是一个 Fragment ,所以在这里进行网络请求等操作肯定比上面说的其他几种要好。
  • DialogFragment 点击外部区域消失这些问题没有 PopupWindow 那么麻烦,自带就有这样的效果。
  • 支持灵活自定义布局,实现不同的样式,和 Activity 关联程度低

DialogFragment 设置常见的注意点

以一个具体代码为例,需要注意的地方都加了注释。

public class BottomDialogFr extends DialogFragment {

    private View frView;
    private Window window;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // 去掉默认的标题
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        frView = inflater.inflate(R.layout.dialog_fr_bottom, null);
        return frView;
    }

    @Override
    public void onStart() {
        super.onStart();
        // 下面这些设置必须在此方法(onStart())中才有效

        window = getDialog().getWindow();
        // 如果不设置这句代码, 那么弹框就会与四边都有一定的距离
        window.setBackgroundDrawableResource(android.R.color.transparent);
        // 设置动画
        window.setWindowAnimations(R.style.bottomDialog);

        WindowManager.LayoutParams params = window.getAttributes();
        params.gravity = Gravity.BOTTOM;
        // 如果不设置宽度,那么即使你在布局中设置宽度为 match_parent 也不会起作用
        params.width = getResources().getDisplayMetrics().widthPixels;
        window.setAttributes(params);
    }

}

如果其内部是一个列表,那么高度可在 onStart() 方法中设置宽度的地方进行设置,布局中设置是无效的。

调用其显示的代码

BottomDialogFr bottomDialogFr = new BottomDialogFr();
bottomDialogFr.show(getSupportFragmentManager(), "DF");

效果图
Android 底部弹框实现,推荐使用 DialogFragment 来做_第1张图片

再贴一下动画的代码
Style


    <style name="bottomDialog">
        <item name="android:windowEnterAnimation">@anim/dialog_fr_in
        "android:windowExitAnimation">@anim/dialog_fr_out
    style>

进入动画


<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="300"
    android:fromYDelta="100%"
    android:toYDelta="0">

translate>

退出动画


<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="300"
    android:fromYDelta="0"
    android:toYDelta="100%">

translate>

到此,核心代码就完了。


Android 技术分享平台
Android 底部弹框实现,推荐使用 DialogFragment 来做_第2张图片

你可能感兴趣的:(Android之旅)