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

Android FrameLayout 中 Button 居左、內容居右的正確佈局結構

     編輯:程式設計綜合問答

問題分析

原佈局嘗試在垂直 LinearLayout 中放置 RelativeLayout(含 Button)與 FrameLayout,期望 Button 左側、FrameLayout 內容右側。但 FrameLayout 默認子視圖靠左,且 RelativeLayout 寬度 wrap_content 導致佈局擠壓。

修正方案:外層包裹水平 LinearLayout 或 RelativeLayout


<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:gravity="center_vertical"
    android:padding="16dp">

    <!-- 左側按鈕 -->
    <Button
        android:id="@+id/buybtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/buy_button" />

    <!-- 右側視頻縮略圖區域,佔據剩餘空間 -->
    <FrameLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_marginStart="16dp">

        <ImageView
            android:id="@+id/videothumbimage"
            android:layout_width="match_parent"
            android:layout_height="170dp"
            android:scaleType="centerCrop"
            android:src="@drawable/demo_thumb_home" />

        <ImageButton
            android:id="@+id/videothumb"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:src="@drawable/button_play_on" />

    </FrameLayout>

</LinearLayout>

關鍵點

  1. 外層水平 LinearLayout:按鈕與 FrameLayout 並列,天然左右分布。
  2. FrameLayout 寬度 0dp + weight=1:佔據按鈕以外的所有剩餘寬度。
  3. 內部 ImageView match_parent:填滿 FrameLayout 寬度。
  4. ImageButton layout_gravity=center:播放圖標居中疊加在縮略圖上。

替代方案:RelativeLayout


<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="16dp">

    <Button
        android:id="@+id/buybtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_centerVertical="true"
        android:text="@string/buy_button" />

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toEndOf="@id/buybtn"
        android:layout_marginStart="16dp">
        <!-- 內容同前 -->
    </FrameLayout>

</RelativeLayout>

總結

FrameLayout 本身不具備「靠右」佈局能力,需在**父容器**層面通過水平 LinearLayout(權重)或 RelativeLayout(相對定位)實現左右分佈。外層包裹一層水平佈局是最直觀穩健的方案。

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