Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

讓 ActionBar 左上角圖示動畫切換:漢堡與返回箭頭之間

編輯:關於 Android 程式設計

Material Design 有個很細膩的細節:側滑菜單展開與收合時,ActionBar 左上角的圖示會在「漢堡」與「返回箭頭」之間連續變形,而不是硬切換。實作起來只需要幾步。

步驟一:頁面骨架是 DrawerLayout

<android.support.v4.widget.DrawerLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    android:id="@+id/main_drawer"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- 內容佈局 -->
    <FrameLayout
        android:id="@+id/main_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <!-- 側滑菜單 -->
    <android.support.design.widget.NavigationView
        android:id="@+id/main_navigation"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/navigation_header"
        app:menu="@menu/menu_drawer" />
</android.support.v4.widget.DrawerLayout>

步驟二:指定箭頭樣式

關鍵是 drawerArrowStyle 與其中的 spinBars:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
</style>

<style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
    <item name="spinBars">true</item>
    <item name="color">@android:color/white</item>
</style>

記得把 AppTheme 套用至 manifest 的 application 標籤下。

步驟三:Activity 中綁定切換器

Activity 繼承 AppCompatActivity,在 onCreate() 中加入(使用 Toolbar 時寫法類似):

ActionBar mActionBar = getSupportActionBar();
if (mActionBar != null) {
    mActionBar.setDisplayHomeAsUpEnabled(true);
    mActionBar.setHomeButtonEnabled(true);
}
// 實現左上角 home 圖示「菜單」與「返回」樣式的動畫切換
// 需在 xml 中配置相關樣式
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
        R.string.drawer_open, R.string.drawer_close);
drawerLayout.setDrawerListener(drawerToggle);

步驟四:同步狀態

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    drawerToggle.syncState();
}

syncState() 的作用是把圖示角度與抽屜的實際狀態對齊。除了 onPostCreate(),任何會導致狀態不一致的時機(例如手動呼叫 openDrawer()、或 configChanges 自行處理了 orientation 變化)都應該補上一次,否則就會出現「抽屜開了但圖示還是漢堡」的尷尬情況。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved