How to center layout inside of Android Dialog?

2019-02-12 10:33发布

I am trying to create a custom Dialog, and have its content centered, but it is always ending up left-aligned. Here is 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>

And my (relevant) code:

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

What am I missing here? Thanks for the assistance.

Image: Screen shot of Dialog problem

4条回答
可以哭但决不认输i
2楼-- · 2019-02-12 10:34

try to edit to this: a:layout_gravity="center_horizontal|center_vertical"
OR
use Relative_Layout and align linear layout to center of parent with fill_parent for Relative wrap_content for Linear.

although it is worked with me on center

查看更多
等我变得足够好
3楼-- · 2019-02-12 10:40

Can you try changing your LinearLayout layout_gravity to just gravity? See the difference explained here: Gravity and layout_gravity on Android

查看更多
放荡不羁爱自由
4楼-- · 2019-02-12 10:41

Modify Dialog's ViewGroup (FrameLayout) which holds your content layout. I use static method and invoke it inside onActivityCreated() in DialogFragments:

/**
 * 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);
}
查看更多
Juvenile、少年°
5楼-- · 2019-02-12 10:41

You're doing layout_gravity which is good, but since you do it to the outmost layout, it can't position itself relative to what's around it.

I think that wrapping the above layout inside another layout would do it

查看更多
登录 后发表回答