代码之家  ›  专栏  ›  技术社区  ›  MEX

不同活动中的同一导航抽屉

  •  210
  • MEX  · 技术社区  · 12 年前

    我制作了一个可工作的导航抽屉,就像在 developer.android.com 网站但现在,我想使用我在NavigationDrawer.class中为应用程序中的多个活动创建的一个导航抽屉。

    我的问题是,如果这里有人能做一个小教程,解释如何使用一个导航抽屉进行多个活动。

    我先看了这个答案 Android Navigation Drawer on multiple Activities

    但它对我的项目不起作用

    public class NavigationDrawer extends Activity {
    public DrawerLayout drawerLayout;
    public ListView drawerList;
    private ActionBarDrawerToggle drawerToggle;
    
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawerToggle = new ActionBarDrawerToggle((Activity) this, drawerLayout, R.drawable.ic_drawer, 0, 0) {
    
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(R.string.app_name);
            }
    
            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(R.string.menu);
            }
        };
        drawerLayout.setDrawerListener(drawerToggle);
    
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);
    
        listItems = getResources().getStringArray(R.array.layers_array);
        drawerList = (ListView) findViewById(R.id.left_drawer);
        drawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, android.R.id.text,
                listItems));
        
        drawerList.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
                drawerClickEvent(pos);
            }
        });
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    
        if (drawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    
    }
    
    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        drawerToggle.syncState();
    }
    
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        drawerToggle.onConfigurationChanged(newConfig);
    }
    }
    

    在本“活动”中,我希望拥有导航抽屉,因此我扩展了“NavigationDrawer”,在其他一些活动中,我想使用相同的导航抽屉

      public class SampleActivity extends NavigationDrawer {...}
    
    13 回复  |  直到 12 年前
        1
  •  189
  •   starball Martin Jorgensen    2 年前

    如果你想要一个导航抽屉,你应该使用碎片。 上周我学习了这个教程,效果很好:

    http://developer.android.com/training/implementing-navigation/nav-drawer.html

    您也可以从本教程下载示例代码,看看如何做到这一点。


    无碎片:

    这是您的基本活动代码:

    public class BaseActivity extends Activity
    {
        public DrawerLayout drawerLayout;
        public ListView drawerList;
        public String[] layers;
        private ActionBarDrawerToggle drawerToggle;
        private Map map;
        
        protected void onCreate(Bundle savedInstanceState)
        {
            // R.id.drawer_layout should be in every activity with exactly the same id.
            drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
            
            drawerToggle = new ActionBarDrawerToggle((Activity) this, drawerLayout, R.drawable.ic_drawer, 0, 0) 
            {
                public void onDrawerClosed(View view) 
                {
                    getActionBar().setTitle(R.string.app_name);
                }
        
                public void onDrawerOpened(View drawerView) 
                {
                    getActionBar().setTitle(R.string.menu);
                }
            };
            drawerLayout.setDrawerListener(drawerToggle);
        
            getActionBar().setDisplayHomeAsUpEnabled(true);
            getActionBar().setHomeButtonEnabled(true);
            
            layers = getResources().getStringArray(R.array.layers_array);
            drawerList = (ListView) findViewById(R.id.left_drawer);
            View header = getLayoutInflater().inflate(R.layout.drawer_list_header, null);
            drawerList.addHeaderView(header, null, false);
            drawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, android.R.id.text1,
                    layers));
            View footerView = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
                    R.layout.drawer_list_footer, null, false);
            drawerList.addFooterView(footerView);
        
            drawerList.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
                    map.drawerClickEvent(pos);
                }
            });
        }
        
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
        
            if (drawerToggle.onOptionsItemSelected(item)) {
                return true;
            }
            return super.onOptionsItemSelected(item);
        
        }
        
        @Override
        protected void onPostCreate(Bundle savedInstanceState) {
            super.onPostCreate(savedInstanceState);
            drawerToggle.syncState();
        }
        
        @Override
        public void onConfigurationChanged(Configuration newConfig) {
            super.onConfigurationChanged(newConfig);
            drawerToggle.onConfigurationChanged(newConfig);
        }
    }
    

    所有其他需要具有导航抽屉的“活动”都应该扩展此“活动”,而不是“活动”本身,例如:

    public class AnyActivity extends BaseActivity
    {
        //Because this activity extends BaseActivity it automatically has the navigation drawer
        //You can just write your normal Activity code and you don't need to add anything for the navigation drawer
    }
    

    XML格式

    <android.support.v4.widget.DrawerLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <!-- The main content view -->
        <FrameLayout
            android:id="@+id/content_frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >
            <!-- Put what you want as your normal screen in here, you can also choose for a linear layout or any other layout, whatever you prefer -->
        </FrameLayout>
        <!-- The navigation drawer -->
        <ListView android:id="@+id/left_drawer"
            android:layout_width="240dp"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:choiceMode="singleChoice"
            android:divider="@android:color/transparent"
            android:dividerHeight="0dp"
            android:background="#111"/>
    </android.support.v4.widget.DrawerLayout>
    

    编辑:

    我自己也遇到过一些困难,所以如果你得到NullPointerExceptions,这里有一个解决方案。在BaseActivity中,将onCreate函数更改为 protected void onCreateDrawer() 。其余的可以保持不变。在扩展BaseActivity的Activities中,按以下顺序放置代码:

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity);
        super.onCreateDrawer();
    

    这就是如何创建一个包含多个活动的导航抽屉的方法,如果您有任何问题,请随时询问。


    编辑2:

    正如@GregDan所说 BaseActivity 也可以覆盖 setContentView() 并在那里调用CreateDrawer:

    @Override 
    public void setContentView(@LayoutRes int layoutResID) 
    { 
        super.setContentView(layoutResID); 
        onCreateDrawer() ;
    }
    
        2
  •  35
  •   WindRider    11 年前

    我找到了最好的实现方式。它在 Google I/O 2014 应用程序。

    他们使用与凯文相同的方法。如果你能从I/O应用程序中提取出所有不需要的东西,你就可以提取出你需要的一切,谷歌保证这是导航抽屉模式的正确使用。 每个活动都有一个可选的 DrawerLayout 作为其主要布局。有趣的部分是如何导航到其他屏幕。它在中实现 BaseActivity 这样地:

    private void goToNavDrawerItem(int item) {
            Intent intent;
            switch (item) {
                case NAVDRAWER_ITEM_MY_SCHEDULE:
                    intent = new Intent(this, MyScheduleActivity.class);
                    startActivity(intent);
                    finish();
                    break;
    

    这与用片段事务替换当前片段的常见方式不同。但是用户没有发现视觉上的差异。

        3
  •  8
  •   jwehrle    8 年前

    因此,这个答案晚了几年,但可能有人会欣赏它。Android给了我们一个新的小工具,它可以更容易地使用一个导航抽屉和几个活动。

    android.support.design.widget.NavigationView是模块化的,在菜单文件夹中有自己的布局。使用它的方式是以以下方式包装xml布局:

    1. 根布局是一个android.support.v4.widget.DrawerLayout,包含两个子项: <include ... /> 有关正在包装的布局(请参见2)和android.support.design.widget.NavigationView。

      <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">
      
      <include
          layout="@layout/app_bar_main"
          android:layout_width="match_parent"
          android:layout_height="match_parent" />
      
      <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_main"
          app:menu="@menu/activity_main_drawer" />
      

    nav_header_main只是一个LinearLayout,其方向=垂直,用于导航绘图的标题。

    activity_main_drawer是res/meenu目录中的一个菜单xml。它可以包含您选择的项目和组。如果你使用AndroidStudio画廊,向导会为你制作一个基本的画廊,你可以看到你的选择。

    1. 应用程序栏布局现在通常是android.support.design.widget.CoordinatorLayout,这将包括两个子项:android.ssupport.design.wridget.AppBarLayout(包含android.software.v7.widget.Toolbar)和 <include ... > 了解您的实际内容(请参见3)。

      <android.support.design.widget.CoordinatorLayout
          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"
          tools:context="yourpackage.MainActivity">
      
       <android.support.design.widget.AppBarLayout
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:theme="@style/AppTheme.AppBarOverlay">
      
          <android.support.v7.widget.Toolbar
              android:id="@+id/toolbar"
              android:layout_width="match_parent"
              android:layout_height="?attr/actionBarSize"
              android:background="?attr/colorPrimary"
              app:popupTheme="@style/AppTheme.PopupOverlay" />
      
      </android.support.design.widget.AppBarLayout>
      
      <include layout="@layout/content_main" />
      

    2. 内容布局可以是您想要的任何布局。这是包含活动主要内容的布局(不包括导航抽屉或应用程序栏)。

    现在,所有这些最酷的地方是,您可以将每个活动包装在这两个布局中,但使NavigationView(请参见步骤1)始终指向activity_main_drawer(或其他)。这意味着您将在所有活动中使用相同的(*)导航抽屉。

    • 它们将不一样 例子 NavigationView的,但公平地说,即使使用上述BaseActivity解决方案,这也是不可能的。
        4
  •  8
  •   Levon Petrosyan    7 年前

    在一组活动中重用通用导航抽屉的最简单方法

    应用程序基线布局.xml

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.v4.widget.DrawerLayout
        android:id="@+id/drawer_layout"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        xmlns:app="http://schemas.android.com/apk/res-auto">
    
        <FrameLayout
            android:id="@+id/view_stub"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
    
        </FrameLayout>
    
        <android.support.design.widget.NavigationView
            android:id="@+id/navigation_view"
            android:layout_width="240dp"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            app:menu="@menu/menu_test"
            />
    </android.support.v4.widget.DrawerLayout>
    

    应用程序基础活动.java

    /*
    * This is a simple and easy approach to reuse the same 
    * navigation drawer on your other activities. Just create
    * a base layout that conains a DrawerLayout, the 
    * navigation drawer and a FrameLayout to hold your
    * content view. All you have to do is to extend your 
    * activities from this class to set that navigation 
    * drawer. Happy hacking :)
    * P.S: You don't need to declare this Activity in the 
    * AndroidManifest.xml. This is just a base class.
    */
    import android.content.Intent;
    import android.content.res.Configuration;
    import android.os.Bundle;
    import android.support.design.widget.NavigationView;
    import android.support.v4.widget.DrawerLayout;
    import android.support.v7.app.ActionBarDrawerToggle;
    import android.support.v7.app.AppCompatActivity;
    import android.view.LayoutInflater;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.FrameLayout;
    
    public abstract class AppBaseActivity extends AppCompatActivity implements MenuItem.OnMenuItemClickListener {
        private FrameLayout view_stub; //This is the framelayout to keep your content view
        private NavigationView navigation_view; // The new navigation view from Android Design Library. Can inflate menu resources. Easy
        private DrawerLayout mDrawerLayout;
        private ActionBarDrawerToggle mDrawerToggle;
        private Menu drawerMenu;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            super.setContentView(R.layout.app_base_layout);// The base layout that contains your navigation drawer.
            view_stub = (FrameLayout) findViewById(R.id.view_stub);
            navigation_view = (NavigationView) findViewById(R.id.navigation_view);
            mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
            mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, 0, 0);
            mDrawerLayout.setDrawerListener(mDrawerToggle);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    
            drawerMenu = navigation_view.getMenu();
            for(int i = 0; i < drawerMenu.size(); i++) {
              drawerMenu.getItem(i).setOnMenuItemClickListener(this);
            }
            // and so on...
        }
    
        @Override
        protected void onPostCreate(Bundle savedInstanceState) {
            super.onPostCreate(savedInstanceState);
            mDrawerToggle.syncState();
        }
    
        @Override
        public void onConfigurationChanged(Configuration newConfig) {
            super.onConfigurationChanged(newConfig);
            mDrawerToggle.onConfigurationChanged(newConfig);
        }
    
        /* Override all setContentView methods to put the content view to the FrameLayout view_stub
         * so that, we can make other activity implementations looks like normal activity subclasses.
         */
        @Override
        public void setContentView(int layoutResID) {
            if (view_stub != null) {
                LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
                ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT);
                View stubView = inflater.inflate(layoutResID, view_stub, false);
                view_stub.addView(stubView, lp);
            }
        }
    
        @Override
        public void setContentView(View view) {
            if (view_stub != null) {
                ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT);
                view_stub.addView(view, lp);
            }
        }
    
        @Override
        public void setContentView(View view, ViewGroup.LayoutParams params) {
            if (view_stub != null) {
                view_stub.addView(view, params);
            }
        }
    
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Pass the event to ActionBarDrawerToggle, if it returns
            // true, then it has handled the app icon touch event
            if (mDrawerToggle.onOptionsItemSelected(item)) {
                return true;
            }
            // Handle your other action bar items...
    
            return super.onOptionsItemSelected(item);
        }
    
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            switch (item.getItemId()) {
                case R.id.item1:
                    // handle it
                    break;
                case R.id.item2:
                    // do whatever
                    break;
                // and so on...
            }
            return false;
        }
    }
    
        5
  •  6
  •   Micro    9 年前

    如果其他人想按照原海报的要求去做,请考虑使用碎片,而不是凯文说的那样。这里有一个关于如何做到这一点的优秀教程:

    https://github.com/codepath/android_guides/wiki/Fragment-Navigation-Drawer

    如果您选择使用活动而不是片段,那么每次导航到新活动时都会遇到导航抽屉被重新创建的问题。这导致每次导航抽屉的呈现都很难看/很慢。

        6
  •  5
  •   Abhinav Saxena    2 年前

    我的建议是:完全不要使用活动,而是使用片段,并在显示第一个片段的容器(例如Linear Layout)中替换它们。[注意:你可以使用导航图来使用这个概念。Compose进一步减少了制作布局XML的需要,所以我们也可以在那里应用它。]

    该代码在Android开发者教程中提供,您只需自定义即可。

    http://developer.android.com/training/implementing-navigation/nav-drawer.html

    建议您在应用程序中使用越来越多的片段,并且应用程序本地应该只有四个基本活动,除了外部活动(例如FacebookActivity)之外,您在AndroidManifest.xml中提到了这些活动:

    1. SplashActivity:不使用片段,使用全屏主题。

    2. LoginSignUpActivity:根本不需要NavigationDrawer,也不需要后退按钮,所以只需使用普通工具栏,但至少需要3或4个片段。不使用动作栏主题

    3. 主页活动或仪表板活动:不使用动作栏主题。在这里,您需要导航抽屉,并且接下来的所有屏幕都将是片段或嵌套片段,直到带有共享抽屉的叶视图。在此活动中,所有设置、用户配置文件等都将作为片段出现在此处。 此处的片段不会添加到后堆栈中,而是从抽屉菜单项中打开。对于需要后退按钮而不是抽屉的碎片,下面有第四种活动。

    4. 没有抽屉的活动。这个活动的顶部有一个后退按钮,里面的片段将共享同一个操作栏。这些片段将被添加到后堆栈中,因为会有导航历史记录。

    [欲了解更多指导,请参阅:https://stackoverflow.com/a/51100507/787399 ]

    编码快乐!!

        7
  •  1
  •   M S Gadag    11 年前

    在baseactivity中更新此代码。不要忘记在活动xml中包含drawer_list_header。

    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
    setContentView(R.layout.drawer_list_header);
    

    不要在你的活动中使用request()。但在点击图像上仍然看不到抽屉。。并且通过拖动,它将在没有列表项的情况下可见。我尝试了很多,但没有成功。需要一些锻炼。。。

        8
  •  1
  •   joninx    11 年前

    根据@Kevin van Mierlo的回答,您也能够实现多个抽屉。例如,默认菜单位于左侧(开始),另一个可选菜单位于右侧,仅在加载确定片段时显示。

    我已经做到了。

        9
  •  1
  •   Volverine    8 年前
    package xxxxxx;
    
    
    
    import android.app.SearchManager;
    import android.content.Context;
    import android.content.Intent;
    import android.widget.SearchView;
    import android.support.design.widget.NavigationView;
    import android.support.v4.widget.DrawerLayout;
    import android.support.v7.app.ActionBarDrawerToggle;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.support.v7.widget.Toolbar;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.Toast;
    
    
    public class loginhome extends AppCompatActivity {
        private Toolbar toolbar;
        private NavigationView navigationView;
        private DrawerLayout drawerLayout;
    
        // Make sure to be using android.support.v7.app.ActionBarDrawerToggle version.
        // The android.support.v4.app.ActionBarDrawerToggle has been deprecated.
        private ActionBarDrawerToggle drawerToggle;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.loginhome);
    
            // Initializing Toolbar and setting it as the actionbar
            toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
    
    
            //Initializing NavigationView
    
    
            navigationView = (NavigationView) findViewById(R.id.nav_view);
    
            //Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
            navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
    
                // This method will trigger on item Click of navigation menu
    
                public boolean onNavigationItemSelected(MenuItem menuItem) {
    
    
                    //Checking if the item is in checked state or not, if not make it in checked state
                    if(menuItem.isChecked()) menuItem.setChecked(false);
                    else menuItem.setChecked(true);
    
                    //Closing drawer on item click
                    drawerLayout.closeDrawers();
    
                    //Check to see which item was being clicked and perform appropriate action
                    switch (menuItem.getItemId()){
    
    
                        //Replacing the main content with ContentFragment Which is our Inbox View;
                        case R.id.nav_first_fragment:
                            Toast.makeText(getApplicationContext(),"First fragment",Toast.LENGTH_SHORT).show();
                             FirstFragment fragment = new FirstFragment();
                            android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                            fragmentTransaction.replace(R.id.frame,fragment);
                            fragmentTransaction.commit();
                            return true;
    
                        // For rest of the options we just show a toast on click
                        case R.id.nav_second_fragment:
                            Toast.makeText(getApplicationContext(),"Second fragment",Toast.LENGTH_SHORT).show();
                            SecondFragment fragment2 = new SecondFragment();
                            android.support.v4.app.FragmentTransaction fragmentTransaction2 = getSupportFragmentManager().beginTransaction();
                            fragmentTransaction2.replace(R.id.frame,fragment2);
                            fragmentTransaction2.commit();
                            return true;
    
                        default:
                            Toast.makeText(getApplicationContext(),"Somethings Wrong",Toast.LENGTH_SHORT).show();
                            return true;
    
                    }
                }
            });
    
            // Initializing Drawer Layout and ActionBarToggle
            drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
            ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.drawer_open, R.string.drawer_close){
    
                @Override
                public void onDrawerClosed(View drawerView) {
                    // Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
                    super.onDrawerClosed(drawerView);
                }
    
                @Override
                public void onDrawerOpened(View drawerView) {
                    // Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
    
                    super.onDrawerOpened(drawerView);
                }
            };
    
            //Setting the actionbarToggle to drawer layout
            drawerLayout.setDrawerListener(actionBarDrawerToggle);
    
            //calling sync state is necessay or else your hamburger icon wont show up
            actionBarDrawerToggle.syncState();
    
    
    
    
    
    
    
        }
    

    将其用于工具栏.xml

    <?xml version="1.0" encoding="utf-8"?>
    
        <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimary"
            android:elevation="4dp"
            android:id="@+id/toolbar"
            android:theme="@style/ThemeOverlay.AppCompat.Dark"
    
    
            >
    
        </android.support.v7.widget.Toolbar>
    

    如果要使用,请将其用于导航标头

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="192dp"
        android:background="?attr/colorPrimaryDark"
        android:padding="16dp"
        android:theme="@style/ThemeOverlay.AppCompat.Dark"
        android:orientation="vertical"
        android:gravity="bottom">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="56dp"
            android:id="@+id/navhead"
            android:orientation="vertical"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true">
    
            <TextView
                android:id="@+id/name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="16dp"
                android:textColor="#ffffff"
                android:text="tanya"
                android:textSize="14sp"
                android:textStyle="bold"
    
                />
    
            <TextView
                android:id="@+id/email"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#ffffff"
                android:layout_marginLeft="16dp"
                android:layout_marginTop="5dp"
                android:text="tanya.com"
                android:textSize="14sp"
                android:textStyle="normal"
    
                />
        </LinearLayout>
        <de.hdodenhof.circleimageview.CircleImageView
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:layout_below="@+id/imageView"
            android:layout_marginTop="15dp"
    
            android:src="@drawable/face"
            android:id="@+id/circleView"
            />
    
    
    
    </RelativeLayout>
    
        10
  •  1
  •   Pavlus    8 年前

    我在科特林是这样做的:

    open class BaseAppCompatActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
    
    protected lateinit var drawerLayout: DrawerLayout
    protected lateinit var navigationView: NavigationView
    @Inject
    lateinit var loginService: LoginService
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d("BaseAppCompatActivity", "onCreate()")
        App.getComponent().inject(this)
        drawerLayout = findViewById(R.id.drawer_layout) as DrawerLayout
    
        val toolbar = findViewById(R.id.toolbar) as Toolbar
        setSupportActionBar(toolbar)
    
        navigationView = findViewById(R.id.nav_view) as NavigationView
        navigationView.setNavigationItemSelectedListener(this)
    
        val toggle = ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
    
        drawerLayout.addDrawerListener(toggle)
        toggle.syncState()
        toggle.isDrawerIndicatorEnabled = true
    
        val navigationViewHeaderView = navigationView.getHeaderView(0)
        navigationViewHeaderView.login_txt.text = SharedKey.username
    }
    private inline fun <reified T: Activity> launch():Boolean{
        if(this is T) return closeDrawer()
        val intent = Intent(applicationContext, T::class.java)
        startActivity(intent)
        finish()
        return true
    }
    
    private fun closeDrawer(): Boolean {
        drawerLayout.closeDrawer(GravityCompat.START)
        return true
    }
    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        val id = item.itemId
    
        when (id) {
            R.id.action_tasks -> {
                return launch<TasksActivity>()
            }
            R.id.action_contacts -> {
                return launch<ContactActivity>()
            }
            R.id.action_logout -> {
                createExitDialog(loginService, this)
            }
        }
        return false
    }
    }
    

    抽屉的活动必须继承此 BaseAppCompatActivity 呼叫 super.onCreate 设置内容(实际上,可以移动到一些init方法)并在其布局中具有相应的id元素之后

        11
  •  1
  •   Farruh Habibullaev    6 年前

    我的答案只是一个概念性的答案,没有任何源代码。这对像我这样的读者来说可能很有用。

    这取决于你最初的方法以及你如何构建你的应用程序。基本上有两种方法。

    1. 您创建一个活动(基本活动),所有其他视图和屏幕都将是片段。该基本活动包含抽屉和协调器布局的实现。这实际上是我更喜欢的方式,因为拥有小的独立片段将使应用程序开发更容易、更顺畅。

    2. 如果你已经用活动开始了应用程序开发,每个屏幕一个,那么你可能会创建基本活动,所有其他活动都从中扩展。基本活动将包含抽屉和协调器实现的代码。任何需要抽屉实现的活动都可以从基本活动扩展。

    我个人更喜欢避免在没有任何组织的情况下使用片段和混合的活动。这会使开发变得更加困难,最终会让你陷入困境。如果你已经完成了,重构你的代码。

        12
  •  0
  •   Hafiz Shahzad Ali Khurram    4 年前

    下面的视频教程对此进行了详细介绍

    Navigation Drawer on Multiple Activities Using Base Activity

    制作一个基本导航抽屉活动并将该基本导航抽屉扩展到您想要在其上显示导航抽屉的所有活动是非常容易的,

    1. 制作导航菜单,标题
    2. 为导航抽屉创建基本活动
    3. 创建内容布局
    4. 基于基本活动的组合菜单、标题和内容布局
    5. 通过使用框架布局,在抽屉菜单中插入每个活动。

    视频中清楚地解释了所有步骤

        13
  •  -1
  •   droidlabel    10 年前

    使用片段在MainActivity中创建导航抽屉。
    初始化MainActivity中的导航抽屉
    现在,在所有其他活动中,您希望使用相同的导航抽屉,将DrawerLayout作为基础,将fragment作为导航抽屉。只需在你的片段中设置android:name,指向你的片段Java文件。您不需要在其他活动中初始化片段。
    你可以通过在谷歌Play商店应用程序等其他活动中滑动来访问Nav Drawer