The Dongster
The Dongster

Reputation: 344

Cannot position a dialog at the center of the view

I want to put a custom dialog at the center point of a specific layout. However the dialog does not go to the center. actually i tried various ways however now i am stuck... such a headache. I tried like the code below.

showCustomDialog(){
            View view = (View) getLayoutInflater().inflate(R.layout.abc, null);
            view.measure(view.MeasureSpec.UNSPECIFIED, view.MeasureSpec.UNSPECIFIED);
            LinearLayout BlackBox = (LinearLayout) view.findViewById(R.id.txt_layout);


            Dialog dialog = new Dialog(this, android.R.style.Theme_Translucent);
            WindowManager.LayoutParams params = new WindowManager.LayoutParams();

            params.x=blackBox.getMeasuredWidth()/2;
            params.y=blackBox.getMeasuredHeight()/2;
            System.out.println("params " + params.x +  " " + params.y);

            dialog.getWindow().setAttributes(params);
            dialog.getWindow().setLayout(view.getMeasuredWidth(), WindowManager.LayoutParams.WRAP_CONTENT);


            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setContentView(R.layout.cust_dialog);
            dialog.show();
    }

The thing is that i want to show the dialog at the center of the "txt_layout" named layout. Thanks for reading this..

Upvotes: 1

Views: 1522

Answers (1)

Corina Gheorghe
Corina Gheorghe

Reputation: 198

Please try this if you haven't tried before:

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

And in the xml please check if you set this params:

 <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <style name="PauseDialog" parent="@android:style/Theme.Dialog">
            <item name="android:windowTitleStyle">@style/PauseDialogTitle</item>
        </style>

        <style name="PauseDialogTitle" parent="@android:style/TextAppearance.DialogWindowTitle">
            <item name="android:gravity">center_horizontal</item>
        </style>
        <style name="DialogWindowTitle">
        <item name="android:maxLines">1</item>
        <item name="android:scrollHorizontally">true</item>
        <item name="android:textAppearance">@android:style/TextAppearance.DialogWindowTitle</item>
        </style>
    </resources>

And you layout should look like this:

  <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
    <RelativeLayout 
        android:id="@+id/relativeLayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"

    android:layout_centerInParent="true"
 >

Upvotes: 1

Related Questions