Android自定义dialog从屏幕底部弹出并且充满屏幕宽度

这是XML布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/white"
    android:orientation="vertical"
    android:padding="10dp">

    <EditText
        android:id="@+id/etCommentbox"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/wathet"
        android:gravity="top"
        android:hint="评论..."
        android:maxLines="6"
        android:minLines="6"
        android:padding="10dp" />

    <TextView
        android:id="@+id/tvComment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:background="@drawable/button_1"
        android:paddingBottom="10dp"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:paddingTop="10dp"
        android:text="评论"
        android:textSize="15sp" />
</LinearLayout>

然后是代码部分

   /**
     * 弹出评论框
     */
    private void showCommentDailog() {
        //R.style.***一定要写,不然不能充满整个屏宽,引用R.style.AppTheme就可以
        final AlertDialog dialog = new AlertDialog.Builder(mContext, R.style.AppTheme).create();
        View view = View.inflate(mContext, R.layout.commentbox_dialog, null);
        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        //设置dialog弹出时的动画效果,从屏幕底部向上弹出
        //window.setWindowAnimations(R.style.dialogStyle);
//        window.getDecorView().setPadding(0, 0, 0, 0);

        //设置dialog弹出后会点击屏幕或物理返回键,dialog不消失
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
        window.setContentView(view);

        //获得window窗口的属性
        WindowManager.LayoutParams params = window.getAttributes();
        //设置窗口宽度为充满全屏
        params.width = WindowManager.LayoutParams.MATCH_PARENT;//如果不设置,可能部分机型出现左右有空隙,也就是产生margin的感觉
        //设置窗口高度为包裹内容
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        params.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE;//显示dialog的时候,就显示软键盘
        params.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;//就是这个属性导致window后所有的东西都成暗淡
        params.dimAmount = 0.5f;//设置对话框的透明程度背景(非布局的透明度)
        //将设置好的属性set回去
        window.setAttributes(params);

        EditText etCommentbox = (EditText) view.findViewById(R.id.etCommentbox);
        TextView tvComment = (TextView) view.findViewById(R.id.tvComment);
        tvComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

猜你喜欢

转载自blog.csdn.net/feelinghappy/article/details/80507073