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