BottomNavigationView为null [英] BottomNavigationView is null

查看:107
本文介绍了BottomNavigationView为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实现 BottomNavigationView 时,我有一个运行时异常,

I have a runtime exception when implementing BottomNavigationView,

原因:java.lang.NullPointerException:尝试在虚拟方法上调用虚拟方法"void com.google.android.material.bottomnavigation.BottomNavigationView.setOnNavigationItemSelectedListener(com.google.android.material.bottomnavigation.BottomNavigationView $ OnNavigationItemSelectedListener)"空对象引用

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.bottomnavigation.BottomNavigationView.setOnNavigationItemSelectedListener(com.google.android.material.bottomnavigation.BottomNavigationView$OnNavigationItemSelectedListener)' on a null object reference

这是我的代码:

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;

import com.google.android.material.bottomnavigation.BottomNavigationView;

public class MainActivity extends AppCompatActivity {
    private BottomNavigationView bottom_nav;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        bottom_nav=  findViewById(R.id.bottom_nav);
        getSupportFragmentManager().beginTransaction().add(R.id.fragTutucu, new Frag1());

        bottom_nav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                Fragment fragment = null;
                switch (menuItem.getItemId()){
                    case R.id.manuel:
                        fragment= new Frag1();
                        return true;
                    case R.id.photo:
                        fragment= new Frag2();
                        return true;
                    case R.id.training:
                        fragment= new Frag3();
                        return true;

                }
                getSupportFragmentManager().beginTransaction().replace(R.id.fragTutucu,fragment);
                return true;

            }
        });


        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

推荐答案

您正在尝试在设置活动视图之前找到BottomNavigationView.您应该先设置内容视图.

You are trying to find the BottomNavigationView before setting the activity view. You should set content view first.

按照以下步骤重新组织代码

Reorganize your code as follow

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // everything other
}

这篇关于BottomNavigationView为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆