How to add a navigation drawer?

后端 未结 4 990
别跟我提以往
别跟我提以往 2021-01-07 06:23

In the following activity, i have a fragment and an image on it. The Fragment is just a darker Action Bar that has a picture on it. I\'m trying to have a left slide menu as

4条回答
  •  南笙
    南笙 (楼主)
    2021-01-07 06:41

    A simple way to add navigation drawer in your activity Works like charm

    activity_main

    
    
    
    
    
    
    
    

    nav_header_main

    
    
    
    

    res > menu > activity_main_drawer

    
    
    
    

    Mainactivity

     Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    
        final DrawerLayout 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.addDrawerListener(toggle);
        toggle.syncState();
        toggle.setDrawerIndicatorEnabled(false);
        Drawable drawable = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_menu, this.getTheme());
        toggle.setHomeAsUpIndicator(drawable);
        toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (drawer.isDrawerVisible(GravityCompat.START)) {
                    drawer.closeDrawer(GravityCompat.START);
                } else {
                    drawer.openDrawer(GravityCompat.START);
                }
            }
        });
    
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
    
                int id = menuItem.getItemId();
    
                if (id == R.id.nav_whitelist) {
                    Toast.makeText(mContext, "Hello world!", Toast.LENGTH_SHORT).show();
                }
    
                DrawerLayout drawer = findViewById(R.id.drawer_layout);
                drawer.closeDrawer(GravityCompat.START);
                return true;
            }
        });
    
    @Override
        public void onBackPressed() {
            DrawerLayout drawer = findViewById(R.id.drawer_layout);
            if (drawer.isDrawerOpen(GravityCompat.START)) {
                drawer.closeDrawer(GravityCompat.START);
            } else {
                super.onBackPressed();
            }
        }
    

    Here :

    Open navigation drawer
    Close navigation drawer 
    

    layout_main

     
    

提交回复
热议问题