我成功地在我的应用程序中实现了导航抽屉,将菜单的每个项目链接到一个片段。目标片段隐藏抽屉切换并显示向上按钮(即箭头图标(,但无论出于何种原因,如果我单击它,它会打开抽屉,我无法返回上一个片段。我必须按后退按钮才能做到这一点。如何更改此行为?是否可以在不在每个片段中添加代码的情况下解决此问题?
我使用什么:
- 导航组件
- 一个活动,一些片段
- 工具栏
- 应用栏配置
主活动
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Setup FTUE conditional navigation
setupNavigation()
setupNavigationDrawer()
appBarConfiguration =
AppBarConfiguration(
setOf(R.id.overviewFragment, R.id.registrationFragment,
R.id.registrationParamFragment), drawerLayout)
setupActionBarWithNavController(navController, appBarConfiguration)
findViewById<NavigationView>(R.id.nav_view)
.setupWithNavController(navController)
}
/**
* Set the toolbar, set the drawerLayout, set the drawerToggle
*/
private fun setupNavigationDrawer() {
toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
drawerLayout = (findViewById<DrawerLayout>(R.id.drawer_layout))
.apply {
setStatusBarBackground(R.color.colorPrimaryDark)
}
drawerToggle = ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open, R.string.close)
drawerToggle.setDrawerIndicatorEnabled(true)
drawerToggle.syncState()
drawerLayout.addDrawerListener(drawerToggle)
}
override fun onPostCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
super.onPostCreate(savedInstanceState, persistentState)
drawerToggle.syncState()
}
/**
* Ensures that the drawer is closed
* before the app switches back to the previous fragment
*/
override fun onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
}
完整存储库:Github
您需要使用导航控制器设置工具栏:
toolbar.setupWithNavController(findNavController(R.id.nav_host_fragment),findViewById(R.id.full_drawer_layout))
这里有更多关于这方面的信息。
为什么不使用继承?创建具有此代码的MonitorCardiacoActivity
,您使用的每个活动都应继承MonitorCardiacoActivity。