2

我是android编程的新手。我想在每个活动中添加抽屉视图。我已经尝试通过扩展主要活动在每个活动中添加抽屉。但它正在崩溃。

请有人指导我如何从头开始在所有活动中添加抽屉。下面我添加了我的HomeActivity

HomeActivity.java

public class Home extends AppCompatActivity implements 
             NavigationView.OnNavigationItemSelectedListener {

    protected DrawerLayout drawer;

    private AppBarConfiguration mAppBarConfiguration;


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


             drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();


        navigationView.setNavigationItemSelectedListener(this);


        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow,
                R.id.nav_tools, R.id.nav_share, R.id.nav_send)
                .setDrawerLayout(drawer)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);



    }





    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.home, menu);
        return true;
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }


    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        return false;
    }


}
4

1 回答 1

1

尝试创建一个单一活动的应用程序,这意味着使用fragments而不是活动。然后您可以轻松地在您的抽屉中创建一个抽屉MainActivity并从那里开始片段。

有关片段的更多信息,请查看此处

以及如何向现有活动添加抽屉。

于 2019-12-27T17:01:02.113 回答