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

本文介绍如何在MaterialDesign中实现侧滑菜单展开/关闭时ActionBar上home图标动画切换的效果。主要步骤包括设置DrawerLayout布局、指定Actionbar样式、继承AppCompatActivity并设置home按钮属性,以及实现home图标动画切换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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();
    }

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

<script type="text/javascript"> $(function () { $('pre.prettyprint code').each(function () { var lines = $(this).text().split('\n').length; var $numbering = $('<ul/>').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($('<li/>').text(i)); }; $numbering.fadeIn(1700); }); }); </script>
### 实现带顶部导航栏、底部导航栏和侧滑菜单的Android布局 #### 实现方案(使用DrawerLayout和ViewPager2) ##### 1. 添加依赖(build.gradle) ```groovy dependencies { implementation 'androidx.appcompat:appcompat:1.6.1' implementation 'com.google.android.material:material:1.9.0' implementation 'androidx.constraintlayout:constraintlayout:2.1.4' implementation "androidx.viewpager2:viewpager2:1.0.0" implementation "androidx.drawerlayout:drawerlayout:1.2.0" } ``` ##### 2. 主布局文件(activity_main.xml) ```xml <?xml version="1.0" encoding="utf-8"?> <androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/drawerLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true"> <!-- 主内容区域 --> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <!-- 顶部导航栏 --> <com.google.android.material.appbar.MaterialToolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:title="应用标题" app:menu="@menu/top_menu"> <!-- 左侧按钮 --> <ImageView android:id="@+id/btnLeft" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_menu" android:layout_gravity="start" android:padding="16dp"/> <!-- 中间标题 --> <TextView android:id="@+id/tvTitle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="主标题" android:textSize="18sp" android:textColor="@android:color/white" android:layout_gravity="center"/> <!-- 右侧按钮 --> <ImageView android:id="@+id/btnRight" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_more" android:layout_gravity="end" android:padding="16dp"/> </com.google.android.material.appbar.MaterialToolbar> <!-- 内容区域 --> <androidx.viewpager2.widget.ViewPager2 android:id="@+id/viewPager" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"/> <!-- 底部导航栏 --> <com.google.android.material.bottomnavigation.BottomNavigationView android:id="@+id/bottomNav" android:layout_width="match_parent" android:layout_height="wrap_content" app:menu="@menu/bottom_menu"/> </LinearLayout> <!-- 左侧侧滑菜单 --> <com.google.android.material.navigation.NavigationView android:id="@+id/navViewLeft" android:layout_width="280dp" android:layout_height="match_parent" android:layout_gravity="start" app:menu="@menu/nav_left_menu"/> <!-- 右侧侧滑菜单 --> <com.google.android.material.navigation.NavigationView android:id="@+id/navViewRight" android:layout_width="280dp" android:layout_height="match_parent" android:layout_gravity="end" app:menu="@menu/nav_right_menu"/> </androidx.drawerlayout.widget.DrawerLayout> ``` ##### 3. Java代码实现(MainActivity.java) ```java public class MainActivity extends AppCompatActivity { private DrawerLayout drawerLayout; private ViewPager2 viewPager; private NavigationView navViewLeft, navViewRight; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 初始化视图 drawerLayout = findViewById(R.id.drawerLayout); viewPager = findViewById(R.id.viewPager); navViewLeft = findViewById(R.id.navViewLeft); navViewRight = findViewById(R.id.navViewRight); ImageView btnLeft = findViewById(R.id.btnLeft); ImageView btnRight = findViewById(R.id.btnRight); BottomNavigationView bottomNav = findViewById(R.id.bottomNav); // 设置ViewPager适配器 ViewPagerAdapter adapter = new ViewPagerAdapter(this); viewPager.setAdapter(adapter); // 顶部左侧按钮点击打开左侧菜单 btnLeft.setOnClickListener(v -> drawerLayout.openDrawer(GravityCompat.START)); // 顶部右侧按钮点击打开右侧菜单 btnRight.setOnClickListener(v -> drawerLayout.openDrawer(GravityCompat.END)); // 底部导航与ViewPager联动 bottomNav.setOnItemSelectedListener(item -> { int itemId = item.getItemId(); if (itemId == R.id.nav_home) { viewPager.setCurrentItem(0); } else if (itemId == R.id.nav_dashboard) { viewPager.setCurrentItem(1); } else if (itemId == R.id.nav_notifications) { viewPager.setCurrentItem(2); } return true; }); // ViewPager页面切换时更新底部导航 viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() { @Override public void onPageSelected(int position) { super.onPageSelected(position); bottomNav.getMenu().getItem(position).setChecked(true); } }); // 侧滑菜单项点击事件 navViewLeft.setNavigationItemSelectedListener(item -> { // 处理左侧菜单点击 drawerLayout.closeDrawer(GravityCompat.START); return true; }); navViewRight.setNavigationItemSelectedListener(item -> { // 处理右侧菜单点击 drawerLayout.closeDrawer(GravityCompat.END); return true; }); } // ViewPager2适配器 private static class ViewPagerAdapter extends FragmentStateAdapter { public ViewPagerAdapter(@NonNull FragmentActivity fragmentActivity) { super(fragmentActivity); } @NonNull @Override public Fragment createFragment(int position) { switch (position) { case 0: return new HomeFragment(); case 1: return new DashboardFragment(); case 2: return new NotificationsFragment(); default: return new HomeFragment(); } } @Override public int getItemCount() { return 3; } } } ``` #### 关键实现点说明 1. **布局结构**: - 使用 `DrawerLayout` 作为根布局实现侧滑菜单 - 主内容区域包含顶部工具栏、ViewPager2 和底部导航栏 - 两个 `NavigationView` 分别作为左右侧滑菜单 2. **功能联动**: - 顶部左右按钮控制对应侧滑菜单的开关 - 底部导航与 ViewPager2 页面联动 - 侧滑菜单项点击后自动关闭菜单 3. **适配器实现**: - 使用 `FragmentStateAdapter` 管理 ViewPager2 的页面 - 每个页面对应一个 Fragment 实现内容分离 4. **资源文件**: - 创建 `res/menu` 目录下的菜单文件: - `top_menu.xml`:顶部工具栏菜单 - `bottom_menu.xml`:底部导航菜单 - `nav_left_menu.xml` 和 `nav_right_menu.xml`:左右侧滑菜单 #### 优化建议 1. **手势控制**: ```java // 添加边缘滑动手势 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED); ``` 2. **状态栏沉浸**: ```java // 在styles.xml中设置 <item name="android:windowTranslucentStatus">true</item> ``` 3. **菜单动画**: ```xml <!-- 在res/anim中创建动画 --> <scale xmlns:android="http://schemas.android.com/apk/res/android" android:duration="300" android:fromXScale="0.8" android:toXScale="1.0"/> ``` 使用 Jetpack Navigation实现类似布局
最新发布
06-30
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值