2016/7/29

在可收合的 App Bar 中加入 Subtitle

可收合的 App Bar (以前叫 Action Bar 後來又一度改成 Tool Bar) 是 Android 平台上新推出的 Material Design 效果。要在開發的 App 中使用這個效果並不難,只要在最新的 Android Studio 中,於新增 Activity 時選擇【File -> New -> Activity -> Scrolling Activity】,並依照「Configure Activity」視窗的欄位填好內容,按下【Finish】按鈕,就可以有一個執行起來如下圖的畫面,頗為無腦。

  

只不過如果要在展開的 App Bar 上加入一個副標題,讓畫面看起來豐富一點,就有一點傷腦筋了!呼叫 setSubtitle 函式在這樣的畫面配置下並不管用,所以必須要在 Layout 的內容上做一些改變。

首先,要先讓 App Bar 展開後的 Title 往上提一點,以便挪出空間可以容納副標題的文字,這個效果可以用 expandedTitleMarginBottom 的屬性來達成, Layout 內容如下:

<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>
view raw layout.xml hosted with ❤ by GitHub

執行後,Activity 的畫面就像下圖一樣:

接下來就是要把副標題加到標題下方,這裡使用 TextView 來達成。要注意的是,TextView 的 Layout 內容必須要加在 CollapsingToolbarLayout 之內,並且 layout_gravity 的屬性要設為 Bottom。為了要對齊主標題的內縮,paddingStart 屬性的內容要設成 32dp。Textview 的內容如下:

<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"/>
view raw textview.xml hosted with ❤ by GitHub

加好了之後,執行 Activity 就會出現如下圖的畫面:

不過,這裡有一點不太完美的地方,在收合到最上方的動畫會出現 Subtitle 的文字與收合後的 Title 重疊。雖然無傷大雅,但還是讓人覺得介意。還好要解決並不困難,Android 的 SDK 裡就已經有現成的方式來處理,就是將 layout_collapseMode 屬性套用在 TextView 上,把內容設定為 parallax 就搞定了。以下是完整的 Layout 內容:

<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>
view raw complete.xml hosted with ❤ by GitHub







0 意見:

張貼留言