Android抽屉布局可能会产生空指针异常

时间:2016-03-27 20:51:01

标签: android android-navigation android-navigation-drawer android-drawer

我一直在我的代码中收到此警告,我开始担心因为我接近完成的最后期限。我的主要活动中有一个DrawerLayout,使用Android Studio自己的导航抽屉活动,但由于现在不推荐使用DrawerLayout setDrawerListener,因此必须对代码稍作更改。

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

    //Firebase reference to main application URL and 'today's' matches
    Firebase mainRef = new Firebase(cons.getFirebaseUrl());

    //DrawerLayout settings for the navigation drawer
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    //Retrieve the navigation drawer and set it's listener for menu item presses
    navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

我收到了drawer.addDrawerListener(toggle)navigationView.setNavigationItemSelectedListener(this)

的警告

在我的代码中,我也在这个方法中接收它:

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) // This line gets the warning {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

提前感谢任何可能知道造成这种情况的人。我已经搜索过这个问题,但我找不到关于帖子已弃用的方法的例子。

1 个答案:

答案 0 :(得分:1)

确保您在support-v7-appcompat中使用了ActionBarDrawerToggle

替换代码drawerLayout.setDrawerListener(actionBarDrawerToggle);

drawerLayout.addDrawerListener(actionBarDrawerToggle);

最后,检查空抽屉和空导航视图,如下所示:

        DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer_layout);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        assert drawer != null;
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        assert navigationView != null;
        navigationView.setNavigationItemSelectedListener(this);