Custom Alert dialog not centered vertically on Android

Viewed 18760

I made a custom alert dialog box to be displayed at the end of my game so that the player can enter its name to save it. The problem is when I call show() on the dialog appears but it's not vertically centered! It's a bit lower than it should and no matter what properties I set in the xml or when using setGravity().

I think this is the same problem as the one mentioned here, but no one gave a proper answer.

Thanks for your help.

For more details, here is my code:

    AlertDialog.Builder builder;

    LayoutInflater inflater = (LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
    View layout = inflater.inflate(R.layout.newrecord,(ViewGroup)findViewById(R.layout.shoot));

    builder = new AlertDialog.Builder(this);
    builder.setView(layout);

    newRecDialog = builder.create();

And here is the code of the first element of the XML layout of newrecord.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:gravity="center"
 android:padding="10dp"
android:baselineAligned="true">

Here is the output screenshot: alt text
(source: free.fr)

11 Answers

If you are dealing with any height and width attributes, you must make sure not to alter the height, since it will alter the position, here is a sample.

     myProgressDialog.show();           
            float widthPecent = 0.60f;
            //order matters
            DisplayMetrics displayMetrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
            int displayWidth = displayMetrics.widthPixels;

        //dont do any adjustments to the height. **************************  <<<<<<<<<<  

            WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
    
            layoutParams.copyFrom(myProgressDialog.getWindow().getAttributes());
            int dialogWindowWidth = (int) (displayWidth * widthPecent);
            layoutParams.width = dialogWindowWidth;

 //dont do any changes to the height. **************************  <<<<<<<<<<  

            myProgressDialog.getWindow().setAttributes(layoutParams);

layoutParams.height = dialogWindowHeight; //comment or remove this line.

Related