Android App 侧边栏菜单的简单实现

Layout

注意事项

想要实现侧边栏,需要配合使用DrawerLayout。因为会用到嵌套布局,所以根布局不能是 ConstraintLayout,最好使用 LinearLayout 布局。

DrawerLayout 布局下再嵌套两个布局,一个放置内容如 LinearLayout,一个放置侧划菜单,这里使用 NavigationView

为了出现侧边栏点击图标和菜单图标,需要自定义一个 ToolBar,放置在内容 Layout 里

重点

侧划菜单 NavigationView 一定要设置 android:layout_gravity="start"

实例



    

        

            
            
        

        
    

Activity

绑定侧划监听事件

private lateinit var mBinding: ActivityEbookBinding
private lateinit var mDrawerToggle: ActionBarDrawerToggle

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    mBinding = ActivityEbookBinding.inflate(layoutInflater)
    setContentView(mBinding.root)
    setSupportActionBar(mBinding.mainMenuEbook)
    initialData()
}

private fun initialData(){
    //初使化侧边栏监听事件
    mDrawerToggle = ActionBarDrawerToggle(this, mBinding.drawerEbook, mBinding.mainMenuEbook, R.string.openDrawerContentDesc, R.string.closeDrawerContentDesc)
    mDrawerToggle.syncState()
    //绑定侧边栏监听事件
    mBinding.drawerEbook.addDrawerListener(mDrawerToggle)

    //侧边栏菜单图标颜色恢复正常,而非默认的灰色
    mBinding.navigationEbook.itemIconTintList = null
    //绑定侧边栏菜单点击事件
    mBinding.navigationEbook.setNavigationItemSelectedListener { item: MenuItem ->
        when(item.itemId){
            R.id.menu_drawer_ebook_setting -> showSnackBar(mBinding.navigationEbook,"menu_drawer_setting")
            R.id.menu_drawer_ebook_close -> finish()
        }
        true
    }
}

你可能感兴趣的:(Android App 侧边栏菜单的简单实现)