如何在android中对齐自定义对话框中心?

前端之家收集整理的这篇文章主要介绍了如何在android中对齐自定义对话框中心?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在处理应用程序,我想将对话框显示为屏幕大小.所以我使用下面的代码.我通过这里得到了解决方Alert message is not displaying in alert dialog box?
AlertDialog.Builder builder = new AlertDialog.Builder(this);
    TextView title = new TextView(this);
    title.setText("DM2");
    title.setBackgroundColor(Color.DKGRAY);
    title.setPadding(10,10,10);
    title.setGravity(Gravity.CENTER);
    title.setTextColor(Color.WHITE);
    title.setTextSize(20);


    TextView text = new TextView(this);  
    text.setText("Hello This text");  
    text.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
    text.setTextSize(20);        
    text.setGravity(Gravity.CENTER);

    //Creates a linearlayout layout and sets it with initial params
    LinearLayout ll = new LinearLayout(this);
    ll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
    ll.setGravity(Gravity.CENTER);
    ll.addView(text); 
    builder.setCustomTitle(title);
    builder.setPositiveButton(
            "Ok",new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int id) {
                    dialog.dismiss();
                }
            }); 

    Dialog d = builder.setView(ll).create();
    //Fills up the entire Screen
    WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
    lp.copyFrom(d.getWindow().getAttributes());
    lp.width = WindowManager.LayoutParams.FILL_PARENT;
    lp.height = WindowManager.LayoutParams.FILL_PARENT;
    d.show();
    d.getWindow().setAttributes(lp);

但我希望对话框出现在中心对齐的位置.现在它显示在窗口的顶部.
我尝试使用lp.garvity = Gravity.center,但没有用.
如果设备方向改变,我需要再按ok按钮关闭对话框.如何解决这个问题?

提前致谢
普什帕

解决方法

我迟到了,但是迟到的时候再好不过了:-)
你可以使用下面的代码:(我也看到了 here)
dialog = new Dialog(activity,android.R.style.Theme_Translucent_NoTitleBar);

dialog.setContentView(R.layout.activity_upload_photo_dialog);

Window window = dialog.getWindow();
window.setLayout(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
window.setGravity(Gravity.CENTER);

//The below code is EXTRA - to dim the parent view by 70%
LayoutParams lp = window.getAttributes();
lp.dimAmount = 0.7f;
lp.flags = LayoutParams.FLAG_DIM_BEHIND;
dialog.getWindow().setAttributes(lp);
//Show the dialog
dialog.show();

希望我帮忙……

原文链接:https://www.f2er.com/android/310424.html

猜你在找的Android相关文章