当Android BottomNavigationView与启动屏幕一起使用时,常常会遇到返回栈的问题。例如,当用户从启动屏幕跳转到BottomNavigationView中的一个片段后,点击设备的返回按钮时,他们可能会直接退出App,而不是返回到启动屏幕。
为了解决这个问题,可以使用以下代码示例:
public class SplashActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//设置启动屏幕布局
setContentView(R.layout.activity_splash);
//启动BottomNavigationView Activity
startActivity(new Intent(this, BottomNavigationViewActivity.class));
//销毁当前Activity
finish();
}
}
public class BottomNavigationViewActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//设置底部导航视图布局
setContentView(R.layout.activity_bottom_navigation_view);
//初始化底部导航栏
initView();
//添加启动屏幕片段到回退栈
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fl_container, new SplashFragment())
.commit();
}
private void initView() {
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation_view);
bottomNavigationView.setOnNavigationItemSelectedListener(
new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem item) {
//在导航菜单项被选中时切换片段
switch (item.getItemId()) {
case R.id.menu_home:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fl_container, new HomeFragment())
.commit();
break;
case R.id.menu_category:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fl_container, new CategoryFragment())
.commit();
break;
case R.id.menu_setting:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fl_container, new SettingFragment())
.commit();
break;
}
return true;
}
});
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
//如果用户已在BottomNavigationViewActivity中,则在新的阶段启动屏幕片段。
getSupportFragmentManager()
.
上一篇:AndroidBottomNavigationView元素图标变灰
下一篇:AndroidBottomNavigationView在每次使用NavigationComponent的时候重新创建Fragments。