5

我在我的代码中不断收到这个警告,我开始担心,因为我接近完成的最后期限。我的主要活动中有一个 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();
    }
}

提前感谢任何可能知道是什么原因的人。我已经搜索了这个问题,但我找不到关于 post deprecated 方法的示例。

4

1 回答 1

1

确保您已ActionBarDrawerToggle在 support-v7-appcompat 中使用过。

替换代码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);
于 2016-08-18T03:15:10.470 回答