5

我一直在我的代碼中收到此警告,我開始擔心,因爲我接近完成截止日期。我在我的主要活動中有一個DrawerLayout,使用Android Studio自己的導航抽屜活動,但不得不稍微改變代碼,因爲DrawerLayout setDrawerListener現在已被棄用。Android抽屜佈局可能會產生空指針異常

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(); 
    } 
} 

在此先感謝的人誰可能有一個想法是什麼導致它。我已經搜索了這個問題,但我無法找到一個關於post-deprecated方法的例子。

回答

0

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

代碼替換drawerLayout.setDrawerListener(actionBarDrawerToggle);

通過drawerLayout.addDrawerListener(actionBarDrawerToggle);

最後,檢查空抽屜和空navigationview這樣的:

 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);