将布局项右对齐,RTL 对齐 Android

Align layout item to the right and RTL on Android

我正在尝试使用此代码将三个项目水平对齐

<LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="right"
            android:layout_gravity="right"
            android:layout_marginTop="10dp"
            android:orientation="horizontal">
            <ImageView
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_marginLeft="10dp"
                android:src="@drawable/address"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textStyle="bold"
                android:text="@string/lbl_address"/>
            <TextView
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:id="@+id/txtAddress" />
        </LinearLayout>

问题是重力从来没有起作用,ImageView 总是从左边开始,其他项目以相同的顺序跟随。

我试图在代码中反转项目顺序,这将适用于 none RTL 语言,但我的应用程序同时针对这两种语言,因此它在支持 RTL 的设备上显示错误。

我也试过 RelativeLayout 但项目相互重叠。

注意:所有语言都应该从右到左开始,这是我想要的行为

因为您在代码中使用 android:layout_width="0dp" android:layout_weight="1"TextView 将使用 space 的其余部分。所以左边的图像会在左边。所以你可以删除 android:layout_weight="1" 并更改 TextView .

的宽度

你可以改变

<TextView
    android:layout_width="0dp"
    android:layout_weight="1"
    android:layout_height="wrap_content"
    android:layout_marginLeft="5dp"
    android:id="@+id/txtAddress" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="5dp"
    android:id="@+id/txtAddress" />

备注

  • 如果你想改变LinearLayout的项目的位置。你可以使用android:gravity="right"

  • 如果你想改变LinearLayout的位置,你可以使用android:layout_gravity="right"

而你的代码是 android:layout_width="match_parent" ,所以 android:layout_gravity="right" 没有效果。

并且您可以在 LinearLayout

中使用 android:layoutDirection="rtl"
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="right"
    android:layout_gravity="right"
    android:layout_marginTop="10dp"
    android:orientation="horizontal"
    android:layoutDirection="rtl"
    xmlns:android="http://schemas.android.com/apk/res/android">

将此属性添加到您的根 LinearLayout 标签:

android:layoutDirection="rtl"

这将使您的视图布局如同用户选择了从右到左的语言,而不管他们实际选择了什么语言。

尝试在AndroidManifest.xml中使用此代码 android:supportsRtl="true" 对于在应用程序中从右开始的支持语言。