Android:实现ActionBar的home图标动画切换

Material Design中一个重要特性是侧滑菜单 展开/关闭 时,ActionBar上的home图标也动画切换。本例要实现的正是这个效果,如图所示:

这里写图片描述

实现这个效果仅需几步:

1.首先,该页面的布局是一个DrawerLayout,代码如下:

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://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>

2.为程序指定Actionbar箭头按钮样式,即如下代码中的DrawerArrowStyle

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <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标签下。
3. 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);

4.在Activity的onPostCreate中添加如下代码,并且在其它可能需要刷新的地方调用drawerToggle.syncState() 方法。

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

本篇完,欢迎讨论、交流。

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值