2016-09-29 100 views
3

我有一個對話框片段,其中包含涉及RecyclerView上方的titleText的線性佈局,最底部的recyclerView下方有一個按鈕。在RecyclerView上設置最大高度

由於recyclerView根據適配器設置的項數來展開或摺疊,因此按鈕有時會被截斷並且不再顯示在屏幕上,因爲recyclerView只覆蓋整個屏幕。

我的問題是,有沒有辦法設置recyclerView的最大高度而不隱藏下面的按鈕。我也不希望只是爲了防止recyclerView不包含任何項目而將視圖設置爲隨機高度,並且它只是一個空白部分。

請讓我知道你是否曾經遇到過這個問題,以及你如何解決這個問題。謝謝!

回答

4

已更新 您可以使用佈局權重輕鬆實現此目的。下面是一個例子:

<?xml version="1.0" encoding="utf-8"?> 
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent"> 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:orientation="vertical"> 

     <TextView 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:gravity="center" 
      android:text="Title" 
      android:textSize="21sp"/> 

     <android.support.v7.widget.RecyclerView 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:paddingBottom="30dp"> 
     </android.support.v7.widget.RecyclerView> 

    </LinearLayout> 

    <Button 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_gravity="bottom" 
     android:text="Submit"/> 
</FrameLayout> 

標題和RecyclerView將根據內容包裝內容,按鈕將始終佔據最低位置。

+0

此解決方案與設置layoutHeight參數基本相同,因爲它仍將80%的視圖分配給recyclerView,即使它是空的並且應該被壓縮? – jensiepoo

+0

感謝您的更新!這是一個很酷的解決方案。但是,基本上這個按鈕只是重疊在recyclerView項目的頂部。 – jensiepoo

+0

只需將填充底部添加到您的回收站視圖即可。 –

0

我建議使用RelativeLayout,因爲它可以處理像您這樣的案例的視圖定位,以便您實際上可以專注於主設計。

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 
    <TextView 
     android:id="@+id/title" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentTop="true" 
     android:text="Some title" /> 
    <android.support.v7.widget.RecyclerView 
     android:id="@+id/recyclerView" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:layout_below="@+id/title" 
     android:layout_above="@+id/button"/> 
    <Button 
     android:id="@+id/button" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentBottom="true" 
     android:layout_centerHorizontal="true" 
     android:gravity="center"/> 
</RelativeLayout> 

上面的XML代碼是您需要的框架代碼。您可以添加邊距和尺寸來控制間距。但無論如何(直到您提供負邊距),您的觀點將永遠不會相互重疊。

使用RelativeLayout的主要技巧是使用XML標籤,如 機器人的能力:layout_below或Android:layout_above或Android:layout_start 或Android:layout_end這完全對齊你的觀點,你 想要的方式。

相關問題