ฉันมี LinearLayout และ XML ของมันคือ:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:id="@+id/button3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button" />
<Button
android:id="@+id/button2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:text="Button" />
<Button
android:id="@+id/button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="Button" />
</LinearLayout>
และผลลัพธ์ก็คือ:
อย่างที่คุณเห็นปุ่มซ้ายบนมีระยะขอบเล็กน้อยจากด้านบน แต่เมื่อโค้ดแสดงว่าไม่มีระยะขอบ ทำไมสิ่งนี้ถึงเกิดขึ้น?
นอกจากนี้ยังมีวิธีแก้ไขแปลก ๆ ซึ่งก็คือหากคุณตั้งค่า gravity:top
ให้กับทุกปุ่ม คุณจะได้รับผลลัพธ์ตามที่คาดหวัง แต่ทำไมถึงจำเป็นด้วยซ้ำ เพราะ linearlayout(horiz)
ควรเริ่มเพิ่มรายการจากซ้ายบนไปขวาบน