1、在登录页面,在校验完身份之后,需要跳转页面,其方法为:
Intent intent = new Intent();
intent.setClass(MainActivity.this, MainActivity2.class);
startActivity(intent);
MainActivity2 为目标页面
2、新建一个Activity,如图所示
然后使用跳转,发现页面Bottom Navigation Activity闪退
3、logcat有以下内容
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.login/com.example.login.MainActivity2}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
。。。。。。
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference
。。。。。。
4、分析以上原因:
在之前的操作中,在themes.xml 将标题改为了NoActionBar
而新的页面中有标题,以下是Bottom Navigation Activity 去掉标题的方法:
在MainActivity2(新页面)中,将
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
注释掉就好了
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMain2Binding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
BottomNavigationView navView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications,R.id.navigation_user)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main3);
// 注释这一行 NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(binding.navView, navController);
}
5、去掉顶部白条
将布局中的这一行去掉
android:paddingTop="?attr/actionBarSize"
然后就好了
补充:在跳转页面之后,通常需要销毁之前的页面,使用finish();方法
如:
//跳转
Intent intent = new Intent();
intent.setClass(MainActivity.this, MainActivity2.class);
startActivity(intent);
//结束当前页面
finish();