首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android LinearLayout 實現左右兩欄文字:插入權重為 1 的空 View 佔位

     編輯:程式設計綜合問答

在水平 LinearLayout 中,若兩個 TextView 皆設 wrap_content 會擠在左側。解決方法是在中間插入一個 layout_weight="1" 的空 View 推開右側元素。

佈局 XML

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Street" />

    <View
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="456546546" />

</LinearLayout>

原理

  • 空 View 寬度 0、權重 1,會佔據剩餘所有水平空間。
  • 左側 TextView 靠左,右側 TextView 被推至最右。
  • 無需嵌套多層佈局,效能較好。

替代方案

若需平均分配寬度,可將兩個 TextView 皆設 layout_weight="1" 並 layout_width="0dp"。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved