Android:无法在NavigationView的共享类中设置onCreateOptionsMenu和onOptionsItemSelected

时间:2019-01-14 21:09:48

标签: android navigation-drawer drawerlayout

我有一个NavigationView可以在活动中放置一个抽屉,并希望在多个活动中使用它

活动:

public class MainActivity extends MenuOptions {

  private DemoFragmentCollectionAdapter adapter;
  private DrawerLayout drawerLayout;
  private NavigationView navigationView;
  private Toolbar toolbar;

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

    toolbar = findViewById(R.id.primaryToolbar);
    setSupportActionBar(toolbar);
    final ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setHomeAsUpIndicator(R.drawable.menu);

    drawerLayout = findViewById(R.id.drawer_layout);
    navigationView = findViewById(R.id.navigation_view);

    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
            int id = menuItem.getItemId();
            switch (id){
                case R.id.cameraIcon:
                    menuItem.setChecked(true);
                    Toast.makeText(MainActivity.this, "Camera", Toast.LENGTH_LONG).show();
                    drawerLayout.closeDrawers();
                    return true;
            }
            return false;
        }
    });
  }
}

MenuOptions类:

public class MenuOptions extends AppCompatActivity {
private DrawerLayout drawerLayout;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main_activity_menu, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    switch (id){
        case R.id.settingsIcon:
            drawerLayout.openDrawer(GravityCompat.START);
            Toast.makeText(getApplicationContext(), "Settings", Toast.LENGTH_LONG).show();
            return true;

        case android.R.id.home:
            drawerLayout.openDrawer(GravityCompat.START);
            Toast.makeText(getApplicationContext(), "Home icon", Toast.LENGTH_LONG).show();
            return true;

            default:return super.onOptionsItemSelected(item);
    }

  }
}

但是当我尝试点按主页按钮(转换为抽屉菜单图标)时,应用崩溃了,并且出现此错误

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.openDrawer(int)' on a null object reference

如何解决此问题?

0 个答案:

没有答案