Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show custom layout alert dialog at center vertical position

xml file layoutdialog appear on parent top but i want to display it on center vertical

I want to display custom dialog at center vertical position but it appears at top.Above the first one is my xml file and second one is output after running in real device. Here is the code of dialog.

    //alert dialog code
    //add theme to display on whole page
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this,      
    android.R.style.Theme_Holo_Light_NoActionBar_TranslucentDecor);
    LayoutInflater inflater = this.getLayoutInflater();
    //custom layout
    View dialogView = inflater.inflate(R.layout.custom_bar, null);
    dialogBuilder.setView(dialogView);

    //button to close dialog box
    Button closeButton = (Button)     
    dialogView.findViewById(R.id.closeButton);
    final AlertDialog alertDialog = dialogBuilder.create();
    closeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            alertDialog.dismiss();
        }
    });
    //show dialog
    alertDialog.show();
like image 440
user2273146 Avatar asked Dec 09 '25 08:12

user2273146


2 Answers

In your main layout of custom_bar put android:gravity="center"

like image 143
Megha Maniar Avatar answered Dec 10 '25 21:12

Megha Maniar


You should write like this.

AlertDialog dialog = new AlertDialog.Builder(this, R.style.Dark).create();
                        if (dialog.getWindow() != null)
                        {
                            Window window = dialog.getWindow();
                            window.setLayout(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
                            window.setGravity(Gravity.CENTER);
                            dialog.getWindow().setBackgroundDrawableResource(android.R.color.background_dark);
                        }

This will show the alert dialog to the center of the screen.

like image 44
Htin Linn Zaw Avatar answered Dec 10 '25 21:12

Htin Linn Zaw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!