为什么我的进度条垂直居中显示不正确?

6
我有以下的布局...
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:background="@drawable/bg_generic_portrait">
  <ListView android:id="@android:id/list"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:background="@drawable/issue_list_item_background_normal"
            android:listSelector="@drawable/issue_background_selector"
            android:divider="@drawable/separator"
    >
  </ListView>
  <ProgressBar
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_gravity="center"
    android:id="@+id/preloader"
    style="@android:style/Widget.ProgressBar.Large"/>

  <TextView android:id="@android:id/empty"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#FF0000"/>
</LinearLayout>

页面效果如下...http://i.stack.imgur.com/Ra5c6.png

我希望预加载器在垂直方向上也能居中,有什么问题吗?


android:layout_width="wrap_content" <--- 尝试将其设置为 fill_parent - Cruceo
5个回答

12

一些情况下,layout_gravity属性不起作用。解决方法是将progress_bar嵌套在一个linear_layout中,并将该布局的gravity设置为center, 代码如下:

<LinearLayout android:orientation="vertical"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:gravity="center">
<ProgressBar
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:id="@+id/preloader"
          style="@android:style/Widget.ProgressBar.Large"/>
</LinearLayout>

我不建议将重力设置为最上面的线性布局,因为如果您更改列表或添加某些内容,可能会发生一些有趣的事情。


不要忘记将FrameLayout设置为父布局,否则其他兄弟布局将被隐藏。 - NightFury

1

您正在尝试做的事情似乎有些问题。在您的布局中,覆盖进度条的ListView可能具有可变高度,具体取决于其内容。因此,使用线性布局无法确保进度条始终位于屏幕中心。

您可以查看ProgressDialog类,该类将在后台加载列表数据时显示进度对话框。

或者,您可以使用RelativeLayout作为顶级布局,并为ProgressBar指定android:layout_centerInParent="true"属性,使ProgressBar和ListView重叠。


1

这是因为您正在使用LinearLayout,我建议您使用RelativeLayout并使用layout_centerVertical属性进行居中,像这样:

<ProgressBar
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_centerVertical="true"
    android:id="@+id/preloader"
    style="@android:style/Widget.ProgressBar.Large"/>

0

我不知道你的 Listview 占据了多少空间,但如果你想真正定义你想要的 x 项,你可能需要使用一个<RelativeLayout>而不是<LinearLayout>


0
在您的父LinearLayout中设置android:gravity="center"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:gravity="center"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent">

请注意,使用“that”甚至会使列表在布局中居中。 - Raykud

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