在Android中,android:layout_centerHorizontal="true"无法正常工作。

3

我正在使用这种布局来使图像和文本居中,但它并没有起作用。我只是简单地使用了android:layout_centerHorizontal="true"。为什么它不起作用我不明白。有人能帮忙解决这个问题吗?

<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ffffff">


        <ImageView
            android:id="@+id/image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="70dp"
            android:background="@drawable/image_tutorial1" />

        <TextView
            android:textSize="14dp"
            android:id="@+id/title"
            android:layout_below="@+id/image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:text="@string/info4"
            android:textColor="#000000"
            android:textStyle="bold" />

    </RelativeLayout>
4个回答

6
在布局中,RelativeLayout的宽度设置为wrap-content,它根本没有占用整个可用宽度。它的内容被居中,但它们的父View正在缩小以适应它们。
尝试将根视图设置为fill_parent
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"

此外,一个 orientation="vertical"gravity="center_horizontal"LinearLayout 也可以更轻松地实现相同的效果。

4

使用RelativeLayout:

android:layout_centerInParent="true"

使用

android:layout_width="wrap_content"

0

你在RelativeLayout中使用方法不正确

    android:layout_width="wrap_content"
    android:layout_height="wrap_content"

应该是这样的

android:layout_height="match_parent"
android:layout_width="match_parent"

0

在RelativeLayout布局下使用[android:layout_centerHorizontal="true"],然后它就会起作用。

<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">

我正在使用相对布局,但它不起作用。我也尝试了线性布局,但那也不起作用。 - ankita gahoi
它只在相对布局下起作用,如果使用相对布局,则可以正常工作。我已经多次使用了这个方法。 - Rohit
让我们在聊天室里继续这个讨论:http://chat.stackoverflow.com/rooms/25014/discussion-between-rohit-and-ankita-gahoi - Rohit
android:layout_marginLeft="250dp" - Rohit
现在我们要离开办公室了,抱歉周末见,下周一早上9:30,祝您周末愉快。 - Rohit
显示剩余5条评论

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