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

Android 聊天介面佈局:RecyclerView 上方 + 底部輸入框

     編輯:程式設計綜合問答

需求場景

類似微信:頂部 RecyclerView 佔滿剩餘空間,底部固定輸入框(含發送按鈕)。

推薦佈局:RelativeLayout

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- 底部輸入區 -->
    <LinearLayout
        android:id="@+id/input_area"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal">
        <EditText android:id="@+id/msg_input"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>
        <Button android:id="@+id/btn_send"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="發送"/>
    </LinearLayout>

    <!-- 訊息列表,置於輸入區上方 -->
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/msg_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/input_area"
        android:layout_alignParentTop="true"/>

</RelativeLayout>

替代方案:ConstraintLayout (現代首選)

<androidx.constraintlayout.widget.ConstraintLayout ...>
    <RecyclerView
        android:id="@+id/msg_list"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toTopOf="@id/input_area"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>

    <LinearLayout
        android:id="@+id/input_area"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent">
        ...
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

關鍵點

  • 底部輸入框 alignParentBottom="true" (Relative) 或 constraintBottom_toBottomOf (Constraint) 固定在螢幕底部。
  • 列表 layout_above="@id/input_area" 或 constraintBottom_toTopOf 自動填滿剩餘高度。
  • RecyclerView 需設定 setHasFixedSize(true) 並配合 LinearLayoutManager 設定 setStackFromEnd(true) 實現新訊息自動滾動到底部。

ConstraintLayout 扁平化視圖層級,渲染效能更佳,建議新專案優先採用。

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