Android编程实现ActionBar的home图标动画切换效果

时间:2021-05-20

本文实例讲述了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() 方法。

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

更多关于Android相关内容感兴趣的读者可查看本站专题:《Android开发动画技巧汇总》、《Android编程之activity操作技巧总结》、《Android视图View技巧总结》、《Android布局layout技巧总结》、《Android开发入门与进阶教程》、《Android资源操作技巧汇总》及《Android控件用法总结》

希望本文所述对大家Android程序设计有所帮助。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章