如何添加导航抽屉?

3
在下面的活动中,我有一个片段和一张图片。该片段只是一个带有图片的较暗操作栏。我正在尝试将左滑菜单作为片段使用,以便在每个活动中都可以使用。
MainActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {

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

主活动XML;

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.bassammetwally.egyptianstreets.MainActivity"
    android:background="#b12828">

    <fragment
        android:layout_width="match_parent"
        android:layout_height="75dp"
        android:name="com.example.bassammetwally.egyptianstreets.Title_bar"
        android:id="@+id/fragment"
        tools:layout="@layout/title_barmenu"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true" />
    <ImageView
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:background="@drawable/logo"
        android:layout_alignTop="@+id/fragment"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="8dp"/>

</RelativeLayout>

每个Activity都应该有的标题栏碎片;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.View;

public class Title_bar extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.title_barmenu, container, false);
    }
}

标题栏片段 XML;

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#8b0404">

</LinearLayout>

我应该如何在标题栏中实现导航抽屉?

Android Studio有一个默认的导航抽屉活动,每个人都可以创建和修改。如果你问我,从头开始制作导航抽屉需要一些工作。 - Clement Osei Tano
@CoolGuyCG 但是我难道不需要为抽屉中的每个项目创建多个NavigationDrawer活动吗?这似乎有点不够。 - ann
您想要将抽屉放在标题“Fragment”内部吗? - Mike M.
@ann 这取决于你想要它做什么。导航抽屉项是一种菜单,你可以像更改菜单内容一样更改其内容,然后onNavigationItemSelected方法也像onOptionsItemSelected一样工作。你只需要根据需要使用switch和case为每个项目进行实现。 - Clement Osei Tano
4个回答

3
尝试像这样做,对于布局文件,你只需要这样:
<?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>

实现起来可能就像这样简单;
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;
    }
}

1

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.


1
步骤1:将以下行添加到应用级别的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'

步骤二 - 将以下代码添加到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>

步骤三:将以下代码添加到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>

步骤4:将以下代码添加到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>

步骤 - 5 将以下代码添加到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>

将以下代码添加到styles.xml中:

第6步:保留html,不要解释。

<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" />

第七步:将以下代码添加到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> 

第八步:将以下代码添加到AndroidManifest.xml中。
  <activity
            android:name=".activities.Home2Activity"
            android:label="Home"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar"
            tools:ignore="LockedOrientationActivity" />

步骤 - 9 将以下代码添加到 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
在你的活动中添加导航抽屉的简单方法 非常好用
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>

导航头部主要

<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>

主活动

 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();
        }
    }

这里:

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

布局主要

 <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" />

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接