在 RelativeLayout 中想給圖片上下添加黑條,但 layout_above="@id/left_strip" 引用的 ID 尚未定義(XML 解析是順序的),導致定位失效。
<RelativeLayout>
<ImageView android:id="@+id/black_strip_top"
android:layout_above="@id/left_strip" /> <!-- 引用後面的 ID -->
<ImageView android:id="@+id/left_strip" ... /> <!-- 定義在後面 -->
</RelativeLayout>
<RelativeLayout>
<ImageView android:id="@+id/left_strip" ... /> <!-- 先定義基準 -->
<ImageView android:id="@+id/black_strip_top"
android:layout_above="@id/left_strip" ... /> <!-- 再引用 -->
<ImageView android:id="@+id/black_strip_below"
android:layout_below="@id/left_strip" ... />
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/center_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="@drawable/your_image" />
<View
android:id="@+id/top_bar"
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_above="@id/center_image"
android:background="#000000" />
<View
android:id="@+id/bottom_bar"
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_below="@id/center_image"
android:background="#000000" />
</RelativeLayout>
@id/xxx 引用的元素必須出現在引用者之前。View 代替 ImageView 做純色條,更輕量。match_parent 寬度配合 layout_above/below 實現橫向鋪滿。調整定義順序,RelativeLayout 相對定位即時生效。