12

我正在尝试创建一个自定义对话框,并将其内容居中,但它总是以左对齐结束。这是aboutdialog.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:a="http://schemas.android.com/apk/res/android"
  a:orientation="vertical"
  a:id="@+id/AboutDialogLayout" 
  a:layout_width="fill_parent" 
  a:layout_height="fill_parent" 
  a:layout_gravity="center_horizontal" 
  a:gravity="center_horizontal">

    <ImageView a:id="@+id/imageView1" 
               a:src="@drawable/pricebook" 
               a:layout_height="wrap_content" 
               a:layout_width="wrap_content"/>
    <TextView a:layout_height="wrap_content"         
              a:textAppearance="?android:attr/textAppearanceLarge" 
              a:id="@+id/textView1" 
              a:text="Price Book" 
              a:layout_width="wrap_content"/>
    <TextView a:layout_height="wrap_content" 
              a:id="@+id/textView2" 
              a:layout_width="wrap_content" 
              a:text="foo"/>
</LinearLayout>

还有我的(相关)代码:

Dialog d = new Dialog(this);
d.setContentView(R.layout.aboutdialog);
d.setTitle(R.string.app_name);

我在这里想念什么?感谢您的帮助。

图片: 对话框问题的屏幕截图

4

4 回答 4

11

尝试对此进行编辑:a:layout_gravity="center_horizontal|center_vertical"

使用Relative_Layout并将线性布局与父级中心对齐,用于线性fill_parent的Relative wrap_content

虽然它和我一起在中心工作

于 2011-09-09T18:28:45.303 回答
2

修改包含您的内容布局的 Dialog 的 ViewGroup (FrameLayout)。我使用静态方法并在 DialogFragments 的 onActivityCreated() 中调用它:

/**
 * Center dialog content inside available space
 * @param dialog
 */
public static void centerDialogContent(Dialog dialog) {
ViewGroup decorView = (ViewGroup) dialog.getWindow().getDecorView();
View content = decorView.getChildAt(0);
FrameLayout.LayoutParams contentParams = (FrameLayout.LayoutParams)content.getLayoutParams();
contentParams.gravity = Gravity.CENTER;
content.setLayoutParams(contentParams);
}
于 2012-06-29T07:13:18.380 回答
0

您正在做的 layout_gravity 很好,但是由于您对最外面的布局进行了操作,因此它无法相对于周围的事物定位自己。

我认为将上述布局包装在另一个布局中就可以了

于 2011-09-09T18:17:45.210 回答
0

您可以尝试将您的 LinearLayout layout_gravity 更改为仅重力吗?请参阅此处解释的差异:Android 上的 Gravity 和 layout_gravity

于 2011-09-09T18:33:31.693 回答