如何设置Dialog的最大高度?

时间:2017-04-06 14:23:43

标签: android android-alertdialog

我想设置最大对话高度。不像dp或px设置的自定义高度。我想设置最大可能的高度来对话相对当前的设备屏幕大小。

4 个答案:

答案 0 :(得分:4)

Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_example);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
lp.height = WindowManager.LayoutParams.MATCH_PARENT;
//lp.height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 330/*height value*/, getResources().getDisplayMetrics()); for custom height value
dialog.getWindow().setAttributes(lp);
dialog.show();

I think this can solve it. I've added two way one is for set dialog height with match parent property and second one is for setting height with custom value

答案 1 :(得分:3)

您无法直接设置最大高度。只是替代,如果高度高于您想要设置的最大高度,则可以重置高度。

WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
int dialogWidth = lp.width;
int dialogHeight = lp.height;

if(dialogHeight > MAX_HEIGHT) {
   d.getWindow().setLayout(width,MAX_HEIGHT);
} 

答案 2 :(得分:2)

可能是addOnLayoutChangeListener()对你有用。

你可以在dialog.show()

之前或之后添加它

这是我的代码:

AlertDialog.Builder builder = new AlertDialog.Builder(this);
    final View view = LayoutInflater.from(this).inflate(R.layout.custom_alertdialog, null);
    builder.setMessage("TestMessage xxxxxxx");
    builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
        }
    });

    builder.setView(view);  //在setView之前调用builder的原有设置控件方法时,能展示设置的控件,之后设置的则不展示!!
    AlertDialog dialog = builder.create();
    dialog.getWindow().setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_bk_cnoneralert));
    //builder.show();   //用这个的话,背景并不会改变,依旧是默认的

    dialog.show();  //必须用这个show 才能显示自定义的dialog window 的背景

    //这种设置宽高的方式也是好使的!!!-- show 前调用,show 后调用都可以!!!
    view.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
        @Override
        public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop,
                                   int oldRight, int oldBottom) {
            int height = v.getHeight();
            int contentHeight = view.getHeight();

            LogUtils.e("高度", height + " / " + " / " + contentHeight);
            int needHeight = 500;

            if (contentHeight > needHeight) {
                //注意:这里的 LayoutParams 必须是 FrameLayout的!!
                //NOTICE : must be FrameLayout.LayoutParams 
                view.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, 
                        needHeight));
            }
        }
    });

答案 3 :(得分:1)

import Foundation

其中d是对话框。此代码将对话框设置为全屏。