如何在Android对话框中居中布局?

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

我在这里错过了什么吗?感谢您的帮助。

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


很奇怪,对我来说它运行良好。你能发一张截图吗? - inazaruk
3
感谢您使用 a: 替代 android:,请问您是如何做到的? - Lalit Poptani
是的,我也检查过了,它运行良好。 - Lalit Poptani
另一个数据点:这段代码在我的Android 2.1(v7)模拟器上可以运行。问题出现在我的Droid X上,它运行的是2.3.3版本。 - Conrad
天啊,我不知道你可以使用: - QED
显示剩余3条评论
4个回答

11

尝试将其编辑为以下内容:a:layout_gravity="center_horizontal|center_vertical"
或者
使用相对布局(Relative_Layout),并使线性布局(Linear)相对于父容器居中,对于相对布局,请使用fill_parent,对于线性布局,请使用wrap_content

虽然在中心工作得很好


4
将整个XML包装在RelativeLayout中即可。两个*Layout的layout_width都需要设置为fill_parent,而两个layout_height都需要设置为wrap_content(至少这是我想要的)。 - Conrad
但问题是RelativeLayout中的子ViewGroup必须具有layout_width=fill_parent才能使其正常工作,有时您不希望内容具有这种行为。请参见下面的解决方案 ;) - Oleksii Malovanyi
这些都对我没用...还有其他的解决方案吗? - Nitesh Verma
我尝试使用LinearLayout + wrap_content(两个重心都是center),但它没有起作用,所以我认为RelativeLayout确实是关键:使用match_parent(替换fill_parent)来设置layout_widthlayout_height,并将layout_gravitygravity设置为center - Neph

2

修改对话框的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);
}

0
你正在使用layout_gravity,这很好,但由于你将其应用于最外层布局,它无法相对于周围的元素定位。
我认为将上述布局包装在另一个布局中就可以解决问题。

将上述XML代码放入另一个LinearLayout中并不会有任何区别。 - Conrad

0

在你的LinearLayout中,每个视图上设置a:layout_gravity="center"怎么样? - Ben Jakuben

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接