[android]如何使LinearLayout布局從右向左水平排列,而不是從左向右排列


方法1:利用android:layout_weight

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <TextView
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="hello_world" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="hello_world2" />
</LinearLayout>

hello_world2的寬度會擠壓hello_world的空間。

效果圖:

方法2:設置LinearLayout屬性  android:gravity="right"

 注:只有在LinearLayout的layout_width="match_parent"才有效。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="right"
    android:orientation="horizontal">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="hello_world" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="hello_world2" />
</LinearLayout>
  

效果圖:

方法三: 從右到左布局(RTL Layout)

從Android 4.2開始,Android SDK支持一種從右到左(RTL,Right-to-Left)UI布局的方式,盡管這種布局方式經常被使用在諸如阿拉伯語、希伯來語等環境中,中國用戶很少使用。不過在某些特殊用途中還是很方便的。

所謂RTL,就是指按平常習慣在左的視圖都會在右側,在右側的視圖都會在左側。例如,在線性布局中第1個子視圖默認都是在左上角的,如果采用RTL布局,默認就在右上角了。

RTL布局默認是關閉的,如果想使用RTL布局,首先要在AndroidManifest.xml文件中將<application>標簽的android:supportsRtl屬性值設為"true",然后需要將相應視圖標簽的android:layoutDirection屬性值設為"rtl"。

注意:RTL布局常用android:layout_marginStart和android:layout_marginEnd來設置兩個視圖的間距。

android:layout_marginStart:如果在LTR布局模式下,該屬性等同於android:layout_marginLeft。如果在RTL布局模式下,該屬性等同於android:layout_marginRight。

android:layout_marginEnd:如果在LTR布局模式下,該屬性等同於android:layout_marginRight。如果在RTL布局模式下,該屬性等同於android:layout_marginLeft。

例如:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:background="#000" 
    android:orientation="horizontal" > 
    <TextView 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:background="#F00" 
        android:text="TextView1" 
        android:textSize="30sp" /> 
    <TextView 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_marginStart="100dp" 
        android:background="#F00" 
        android:text="TextView2" 
        android:textSize="30sp" /> 
</LinearLayout> 

 效果如下:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM