Android抽屉布局可能会产生空指针异常
我一直在我的代码中收到这个警告,我开始担心,因为我快到完成的最后期限了。我的主要活动中有一个抽屉布局,使用Android Studio自己的导航抽屉活动,但不得不对代码做一些细微的更改,因为抽屉布局setDrawerListener现在已不推荐使用Android抽屉布局可能会产生空指针异常,android,android-navigation,navigation-drawer,android-drawer,Android,Android Navigation,Navigation Drawer,Android Drawer,我一直在我的代码中收到这个警告,我开始担心,因为我快到完成的最后期限了。我的主要活动中有一个抽屉布局,使用Android Studio自己的导航抽屉活动,但不得不对代码做一些细微的更改,因为抽屉布局setDrawerListener现在已不推荐使用 protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.acti
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(切换)
和navigationView.setNavigationItemSelectedListener(此)
在我的代码中,我还通过以下方法接收它:
@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();
}
}
提前感谢任何可能知道是什么原因的人。我已搜索了此问题,但找不到有关后弃用方法的示例。请确保您在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);