可收合的 App Bar (以前叫 Action Bar 后來又一度改成 Tool Bar) 是 Android 平臺上新推出的 Material Design 效果。要在 App 中使用這個效果并不難墓卦,只要在最新的 Android Studio 中飘痛,于新增 Activity 時選擇【File -> New -> Activity -> Scrolling Activity】奶浦,并依照 “Configure Activity” 窗口的欄位填好內(nèi)容科汗,按下【Finish】按鈕佛南,就可以有一個運行起來如下圖的畫面,頗為無腦灭翔。
只不過如果要在展開的 App Bar 上加入一個副標題魏烫,讓畫面看起來豐富一點,就有一點燒腦了肝箱!調(diào)用 setSubtitle
函式在這樣的畫面配置下并不管用哄褒,所以必須要在 Layout 的內(nèi)容上做一些改變。
首先煌张,要先讓 App Bar 展開后的 Title 往上提一點读处,以便挪出空間可以容納副標題的文字,這個效果可以用 expandedTitleMarginBottom
的屬性來達成唱矛, Layout 內(nèi)容如下:
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginBottom="40dp"
app:layout_scrollFlags="scroll|exitUntilCollapsed|snap">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="@style/AppTheme.PopupOverlay"/>
</android.support.design.widget.CollapsingToolbarLayout>
運行后,Activity 的畫面就像下圖一樣:
接下來就是要把副標題加到標題下方井辜,這里使用 TextView 來達成绎谦。要注意的是,TextView 的 Layout 內(nèi)容必須要加在 CollapsingToolbarLayout
之內(nèi)粥脚,并且 layout_gravity
的屬性要設為 Bottom
窃肠。為了要對齊主標題的縮進,paddingStart
屬性的內(nèi)容要設成 32dp
刷允。Textview 的內(nèi)容如下:
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:paddingStart="32dp"
android:paddingEnd="8dp"
android:paddingBottom="8dp"
android:text="Subtitle goes here"
android:textColor="@android:color/white"
android:textSize="20sp"/>
加好了之后冤留,運行,Activity 就會出現(xiàn)如下圖的畫面:
不過树灶,這里有一點不太完美的地方纤怒,在收合到最上方的動畫會出現(xiàn) Subtitle 的文字與收合后的 Title 重疊。雖然無傷大雅天通,但還是讓人覺得介意泊窘。還好要解決并不困難,Android 的 SDK 里就已經(jīng)有現(xiàn)成的方式來處理像寒,就是將 layout_collapseMode
屬性套用在 TextView 上烘豹,把內(nèi)容設定為 parallax
就搞定了。以下是完整的 Layout 內(nèi)容:
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginBottom="40dp"
app:layout_scrollFlags="scroll|exitUntilCollapsed|snap">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:paddingStart="32dp"
android:paddingEnd="8dp"
android:paddingBottom="8dp"
android:text="Subtitle goes here"
android:textColor="@android:color/white"
android:textSize="20sp"
app:layout_collapseMode="parallax"/>
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="@style/AppTheme.PopupOverlay"/>
</android.support.design.widget.CollapsingToolbarLayout>