无法在视图的中心放置对话框

时间:2015-03-13 08:44:47

标签: android dialog position center

我想在特定布局的中心点放置一个自定义对话框。 但是,对话框不会转到中心。实际上我尝试了各种各样的方法然而现在我被卡住......这么头疼。 我试过下面的代码。

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"的中心显示对话框。命名布局。 感谢您阅读此内容..

1 个答案:

答案 0 :(得分:0)

如果你以前没有尝试过,请试试这个:

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