Sharing NavigationView with all the Activities?

蓝咒 提交于 2019-12-04 19:34:46

问题


How do we share Drawer with all the activities?

In the lister: onNavigationItemSelected of setNavigationItemSelectedListener we can get the id and navigate to it. What I am looking for is something like this:

private void initDrawerLayout() {
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

        NavigationView navView = (NavigationView) findViewById(R.id.navigation_view);
        navView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {


        Intent intent;
        int id = menuItem.getItemId();

        switch(id) {

            case R.id.home:
            case R.id.drawer_home:
            // call activity instead of adding/replacing fragment
            return true;

            case R.id.drawer_gallery:
            // call activity instead of adding/replacing fragment
            intent = new Intent(MainActivity.this, GalleryActivity.class);
            startActivity(intent);
            return true;

            case R.id.drawer_about:
            // call activity instead of adding/replacing fragment
            intent = new Intent(MainActivity.this, AboutActivity.class);
            startActivity(intent);
            return true;
        ...
        }
        ...

I know I can make all the menuItems add/replace Fragment, but then handling fragments and memory management is a big pain.

Instead I want each menuItem select/click to invoke Activity. i.e. each MainMenuItem to have Activity and those will hold fragments with complex layouts.

All I want to do is have each main menu item be an Activity instead of a Fragment.

And all these activities can share same DrawerNavigation.

Is this the recommended way? Or do we always add Fragments for NavigationDrawer item clicks??

Should I add NavigationView to BaseActivity and then extend all activities from there??

Following this new guide about Support Design lib


回答1:


I found the answer using this SO answer

Extending is the right way. Just override setContentView in the right way...




回答2:


I am a bit confused here as well. After finding very little information on this I tried to extend my subclass

public class NewActivity extends MainActivity{
     ...
}

However, this alone didn't do anything. the MainActivity has a fully functioning NavigationView that will navigate to each activity..Only thing that is left is sharing it with each activity.



来源:https://stackoverflow.com/questions/30822326/sharing-navigationview-with-all-the-activities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!