Android Studio入学1-5:跳转Bottom Navigation Activity(出错的可能解决方法)

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();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

第四维度4

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值