为底部导航项设置点击事件,当用户点击返回按钮时,触发底部导航项的点击事件,而不是直接退出应用程序。
示例代码:
// 声明底部导航栏项 private BottomNavigationView bottomNavigationView;
// 将底部导航栏项与布局文件中的 BottomNavigationView 控件绑定 bottomNavigationView = findViewById(R.id.bottomNavigationView);
// 设置底部导航栏项的点击事件 bottomNavigationView.setOnNavigationItemSelectedListener( new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.navigation_home: // 处理 Home 点击事件 return true; case R.id.navigation_dashboard: // 处理 Dashboard 点击事件 return true; case R.id.navigation_notifications: // 处理 Notifications 点击事件 return true; } return false; } } );
// 拦截返回按钮事件,转发给底部导航栏项的点击事件处理 @Override public void onBackPressed() { MenuItem homeItem = bottomNavigationView.getMenu().getItem(0); if (bottomNavigationView.getSelectedItemId() != homeItem.getItemId()) { bottomNavigationView.setSelectedItemId(homeItem.getItemId()); } else { super.onBackPressed(); } }
上一篇:按下时颜色改变
下一篇:按下鼠标按钮进行循环绘制线条