How to add a navigation drawer?

后端 未结 4 988
别跟我提以往
别跟我提以往 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

    <androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">
    
    <include
        layout="@layout/layout_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    
    <com.google.android.material.navigation.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />
    
    </androidx.drawerlayout.widget.DrawerLayout>
    

    nav_header_main

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="176dp"
    android:background="@color/colorPrimary"
    android:gravity="bottom"
    android:orientation="vertical"
    android:paddingLeft="16dp"
    android:paddingTop="16dp"
    android:paddingRight="16dp"
    android:paddingBottom="16dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">
    
    </LinearLayout>
    

    res > menu > activity_main_drawer

    <menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/nav_home"
        android:icon="@drawable/ic_touch"
        android:title="Whitelisted Apps" />
    </menu>
    

    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 :

    <string name="navigation_drawer_open">Open navigation drawer</string>
    <string name="navigation_drawer_close">Close navigation drawer</string> 
    

    layout_main

     <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
    
    0 讨论(0)
  • 2021-01-07 06:42

    Use the built-in Android studio navigation bar activity. I'm not sure how to use the Titlebar part (

    getActionBar().setCustomView()
    ) but everything is already given. You don't need to create a Fragment in the XML.

    0 讨论(0)
  • 2021-01-07 06:48

    Try something like this, for the layout file, you just need

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:openDrawer="start">
    
    
    <!-- Main content when drawer is closed -->
        <include
            layout="@layout/app_bar_nav"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    <!-- The drawer, you can change the menu contents dynamically -->
        <android.support.design.widget.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:fitsSystemWindows="true"
            app:headerLayout="@layout/nav_header"
            app:menu="@menu/menu_nav" />
    
    </android.support.v4.widget.DrawerLayout>
    

    And the implementation could be as simple as this;

    package com.example;
    
    
    public class NavigationDrawer extends AppCompatActivity
            implements NavigationView.OnNavigationItemSelectedListener {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_navigation_drawer);
            //You should remove this if you have no intent of using it
            //And if you uset it, to prevent double actionbars, use a style with no actionbar
            //Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);//I like setting custom actionbar
            //setSupportActionBar(toolbar);
    
    
            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                    this, drawer, toolbar, "Open drawer", "Close drawer");
            drawer.setDrawerListener(toggle);
            toggle.syncState();
    
            NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
            navigationView.setNavigationItemSelectedListener(this);
        }
    
        @Override
        public void onBackPressed() {
            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            if (drawer.isDrawerOpen(GravityCompat.START)) {
                drawer.closeDrawer(GravityCompat.START);
            } else {
                super.onBackPressed();
            }
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.note_home, menu);
            return true;
        }
    
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            return true;//or super.onOptionsItemSelected, false won't show menu
        }
    
    
        @SuppressWarnings("StatementWithEmptyBody")
        @Override
        public boolean onNavigationItemSelected(MenuItem item) {
            // Handle navigation view item clicks here.
            int id = item.getItemId();
            switch (id) {
                case R.id.nav_camera:
                    break;
                case R.id.nav_gallery:
                    break;
    
                case R.id.nav_schedule:
                    break;
                case R.id.nav_manage:
                    //do someting silly
                    break;
            }
            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);
            return true;
        }
    }
    
    0 讨论(0)
  • 2021-01-07 06:57

    Step - 1 add lines into app level Build.gradle

      implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
        implementation 'androidx.navigation:navigation-fragment:2.3.0'
        implementation 'androidx.navigation:navigation-ui:2.3.0'
        implementation 'com.google.android.material:material:1.1.0'
    

    Step - 2 file add below code into activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/drawer_layout2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:openDrawer="start">
    
        <include
            layout="@layout/app_bar_main"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    
        <com.google.android.material.navigation.NavigationView
            android:id="@+id/nav_view2"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:fitsSystemWindows="true"
            app:headerLayout="@layout/nav_header_main2"
            app:itemIconSize="30dp"
            app:menu="@menu/activity_main_drawer2" />
        <!--    app:theme="@style/NavigationDrawerStyle"-->
    </androidx.drawerlayout.widget.DrawerLayout>
    

    Step - 3 add below code into layout/app_bar_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.coordinatorlayout.widget.CoordinatorLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <com.google.android.material.appbar.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:elevation="0dp"
            android:theme="@style/AppTheme.AppBarOverlay">
    
            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="@color/darkblue"
                app:popupTheme="@style/AppTheme.PopupOverlay" />
        </com.google.android.material.appbar.AppBarLayout>
    
        <include layout="@layout/content_main2" />
    </androidx.coordinatorlayout.widget.CoordinatorLayout>
    

    Step - 4 add below code into layout/nav_header_main2.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="bottom"
        android:orientation="horizontal"
        android:paddingHorizontal="20dp"
        android:paddingTop="30dp"
        android:theme="@style/ThemeOverlay.AppCompat.Dark">
    
        <ImageView
            android:id="@+id/img_close_nav"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_margin="15dp"
            app:srcCompat="@mipmap/ic_launcher" />
    
        <TextView
            android:id="@+id/txt_user_name_drawer"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="User Name"
            android:layout_marginVertical="10dp"
            android:textColor="@android:color/black"
            android:textStyle="bold"
            android:textSize="16sp"/>
    </LinearLayout>
    

    Step - 5 add below code into menu/activity_main_drawer2.xml

     <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        tools:showIn="navigation_view">
        <group android:checkableBehavior="single">
            <item
                android:id="@+id/nav_profile"
                android:icon="@drawable/ic_launcher_background"
                android:title="My Profile" />
            <item
                android:id="@+id/nav_orders"
                android:icon="@drawable/ic_launcher_background"
                android:title="My Orders" />
            <item
                android:id="@+id/nav_about_us"
                android:icon="@mipmap/ic_launcher"
                android:title="About Us" />
            <item
                android:id="@+id/nav_terms_and_conditions"
                android:icon="@drawable/ic_launcher_background"
                android:title="Terms &amp; Conditions" />
            <item
                android:id="@+id/nav_share"
                android:icon="@drawable/ic_launcher_background"
                android:title="Share" />
            <item
                android:id="@+id/nav_log_out"
                android:icon="@drawable/ic_launcher_background"
                android:title="Logout" />
        </group>
    </menu>
    

    Step - 6 add below code into styles.xml

    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
        <item name="windowActionModeOverlay">true</item>
    </style>
    
    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
    
    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
    

    Step - 7 add below code into layout/content_main2.xml

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/darkblue"
        android:orientation="vertical"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">
    
      <\RelativeLayout> 
    

    Step - 8 add below code into AndroidManifest.xml

      <activity
                android:name=".activities.Home2Activity"
                android:label="Home"
                android:screenOrientation="portrait"
                android:theme="@style/AppTheme.NoActionBar"
                tools:ignore="LockedOrientationActivity" />
    

    Step - 9 add below code into Home2Activity.java

    import androidx.appcompat.app.ActionBarDrawerToggle;
    import androidx.appcompat.app.AppCompatActivity;
    import androidx.appcompat.widget.Toolbar;
    import androidx.drawerlayout.widget.DrawerLayout;
    
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import com.google.android.material.navigation.NavigationView;
    
    public class Home2Activity extends AppCompatActivity {
        DrawerLayout drawer2;
        DrawerLayout.DrawerListener drawerListener2;
        NavigationView navigationView2;
        Toolbar toolbar2;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            allocatememory();
            setSupportActionBar(toolbar2);
            getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_launcher_background);  // set drawable icon
            getSupportActionBar().setHomeButtonEnabled(true);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("Home");
            sliderDrawer();
        }
    
        private void allocatememory() {
            toolbar2 = findViewById(R.id.toolbar);
            drawer2 = findViewById(R.id.drawer_layout2);
            navigationView2 = findViewById(R.id.nav_view2);
        }
    
        private void sliderDrawer() {
            View headerView = navigationView2.getHeaderView(0);
            TextView navUsername = (TextView) headerView.findViewById(R.id.txt_user_name_drawer);
            navUsername.setText("User Name2");
            drawerListener2 = new ActionBarDrawerToggle(this, drawer2, toolbar2, R.string.navigation_drawer_open,
                    R.string.navigation_drawer_close) {
                @Override
                public void onDrawerClosed(View drawerView) {
                    super.onDrawerClosed(drawerView);
                }
    
                @Override
                public void onDrawerOpened(View drawerView) {
                    super.onDrawerOpened(drawerView);
                }
    
                @Override
                public void onDrawerSlide(View drawerView, float slideOffset) {
                }
            };
            View headerview = navigationView2.getHeaderView(0);
            headerview.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    drawer2.close();
                }
            });
            navigationView2.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(MenuItem menuItem) {
                    int id = menuItem.getItemId();
                    switch (id) {
                        case R.id.nav_profile: {
                            startActivity(new Intent(Home2Activity.this, TestActivity.class));
                        }
                        break;
                        case R.id.nav_share: {
                            //ShareApp();
                        }
                        break;
                        case R.id.nav_orders: {
                            startActivity(new Intent(Home2Activity.this, TestActivity.class));
                        }
                        break;
                        case R.id.nav_log_out: {
                            //storage.write("id", -1);
                            Toast.makeText(Home2Activity.this, "Logged out successfully", Toast.LENGTH_LONG).show();
                            Intent intent = new Intent(Home2Activity.this, TestActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(intent);
                            finishAffinity();
                        }
                        break;
                        case R.id.nav_about_us: {
                            Intent intent = new Intent(Home2Activity.this, TestActivity.class);
                            intent.putExtra("where", 1);
                            startActivity(intent);
                        }
                        break;
                        case R.id.nav_terms_and_conditions: {
                            Intent intent = new Intent(Home2Activity.this, TestActivity.class);
                            intent.putExtra("where", 2);
                            startActivity(intent);
                        }
                        break;
                    }
                    return false;
                }
            });
        }
    }
    
    0 讨论(0)
提交回复
热议问题