2015-10-05 81 views
116

我有以下佈局:添加工具欄下面意見CoordinatorLayout

<android.support.design.widget.CoordinatorLayout 
    android:id="@+id/main_content" 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <android.support.design.widget.AppBarLayout 
     android:id="@+id/appBar" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:theme="@style/ThemeOverlay.AppCompat.ActionBar"> 

     <android.support.v7.widget.Toolbar 
      android:id="@+id/toolbar" 
      android:layout_width="match_parent" 
      android:layout_height="?attr/actionBarSize" 
      android:background="?attr/colorPrimary" 
      app:layout_scrollFlags="scroll|enterAlways" 
      app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/> 

    </android.support.design.widget.AppBarLayout> 

    <FrameLayout 
     android:id="@+id/content" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     /> 
</android.support.design.widget.CoordinatorLayout> 

我添加Fragment S插入FrameLayout,替換它們。我的一個Fragment S的是一個列表,它具有以下佈局:

<android.support.v7.widget.RecyclerView 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    android:id="@+id/recyclerView" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    app:layout_behavior="@string/appbar_scrolling_view_behavior"/> 

我在這裏的問題是,工具欄上繪製列表。我試圖通過將CoordinatorLayout的內容包裝成LinearLayout來解決該問題,解決了透支問題,但這樣appbar滾動行爲不再起作用。

任何幫助非常感謝!

回答

254

就拿屬性

app:layout_behavior="@string/appbar_scrolling_view_behavior" 

關閉RecyclerView,並把它放在FrameLayout您嘗試下Toolbar顯現。

我發現滾動視圖行爲所做的一件重要事情是在工具欄下面佈局組件。因爲FrameLayout有一個將滾動的後代(RecyclerView),所以CoordinatorLayout將獲得用於移動Toolbar的滾動事件。


另一個要注意的:這個佈局行爲將導致FrameLayout高度的尺寸彷彿Toolbar已經滾動,並與Toolbar完全顯示整個視圖僅僅是被推下該視圖的底部低於CoordinatorLayout的底部。

這對我來說是一個驚喜。我希望在工具欄上下滾動時動態調整視圖的大小。因此,如果在視圖底部有一個固定組件的滾動組件,在完全滾動Toolbar之前,您將不會看到該底部組件。

所以,當我想在用戶界面的底部錨定一個按鈕,我工作圍繞這通過將按鈕CoordinatorLayoutandroid:layout_gravity="bottom")的底部,並增加了下邊距等於按鈕的高度視圖下方工具欄。

+1

非常感謝,這真的有用!我之後唯一的問題是,如果工具欄被移出,在用另一個「Fragment」替換包含列表的'Fragment'後,它不會返回。我設法手動顯示工具欄[this](http://stackoverflow.com/a/30729413/747412)的方式。 – WonderCsabo

+0

哇。我一直認爲Fragment自己的佈局完全取代了FrameLayout的「佔位符」,但我發現情況並非如此。感謝這個答案!這對我幫助很大。 –

+0

不錯,工作。 –

34

我設法加入到解決這個問題:

機器人:layout_marginTop = 「?ATTR/actionBarSize」

到FrameLayout裏,像這樣:

<FrameLayout 
     android:id="@+id/content" 
     android:layout_marginTop="?attr/actionBarSize" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     /> 
+4

而不是增加marginTop添加應用程序:layout_behavior =「@字符串/ appbar_scrolling_view_behavior」 –

+2

完美的解決方案時,@字符串/ appbar_scrolling_view_behavior不可 –

+1

不會對CollapsingToolbarLayout –