无法将对话框定位在视图的中心

Cannot position a dialog at the center of the view

我想将自定义对话框放在特定布局的中心点。 但是,对话框不会转到中心。实际上我尝试了各种方法但是现在我被卡住了......真让人头疼。 我试过下面的代码。

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();
    }

问题是我想在 "txt_layout" 命名布局的中心显示对话框。 感谢您阅读本文..

如果您以前没有尝试过,请尝试一下:

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

并且在 xml 中请检查您是否设置了此参数:

 <?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>

你的布局应该是这样的:

  <?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"
 >