设置导航视图侦听器失败

时间:2018-10-21 11:16:36

标签: android listener navigation-drawer nullreferenceexception

我的MainActivity.java类中具有以下代码:

private NavigationView nvDrawer;

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

        // Set a Toolbar to replace the ActionBar.
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        // Find our drawer view
        mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);

        // Setup drawer view
        setupDrawerContent(nvDrawer);
    }

private void setupDrawerContent(NavigationView navigationView) {

        navigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(MenuItem menuItem) {
                        selectDrawerItem(menuItem);
                        return true;
                    }
                });
    }

LogCat的输出显示以下内容:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.NavigationView.setNavigationItemSelectedListener(android.support.design.widget.NavigationView$OnNavigationItemSelectedListener)' on a null object reference
        at com.gamecodeschool.fragmentnavigationdrawer.MainActivity.setupDrawerContent(MainActivity.java:54)
        at com.gamecodeschool.fragmentnavigationdrawer.MainActivity.onCreate(MainActivity.java:37)
        at android.app.Activity.performCreate(Activity.java:6237)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
        at android.app.ActivityThread.-wrap11(ActivityThread.java) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:148) 
        at android.app.ActivityThread.main(ActivityThread.java:5417) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

因此,传递给 setupDrawerContent()方法的 navigationView 参数是一个空对象,在其上调用listener方法会导致此异常。有什么建议可以解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

您的nvDrawer未分配。您应该在调用设置导航视图并将其分配给变量nvDrawer之前找到导航视图。