如何在android中创建自定义导航抽屉

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21796209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 05:05:32  来源:igfitidea点击:

How to create a custom navigation drawer in android

androidandroid-listviewnavigation-drawer

提问by chathura

Hi I'm trying to create a navigation drawer similar to gmail app navigation drawer. I follow the developer site but it only specify about basic implementation. But I need to customize the navigation according to my specifications.

嗨,我正在尝试创建一个类似于 gmail 应用程序导航抽屉的导航抽屉。我关注开发者网站,但它只指定了基本实现。但是我需要根据我的规格自定义导航。

  1. I need to add a header to categorize the list item in Drawer
  2. I need a radio button to select some of my options
  1. 我需要添加一个标题来对抽屉中的列表项进行分类
  2. 我需要一个单选按钮来选择我的一些选项

How can I do this?

我怎样才能做到这一点?

回答by JJD

The tutorial Android Custom Navigation Drawer (via archive.org)contains a basicand a customproject. The latter shows how to setup a Navigation Drawer as shown in the screenshot:

Android 自定义导航抽屉教程(通过 archive.org)包含一个基本项目和一个自定义项目。后者显示了如何设置导航抽屉,如屏幕截图所示:

NavigationDrawerCustom

NavigationDrawerCustom

The source code of the projects (via archive.org)is available for download.

项目源代码(通过 archive.org)可供下载。



The is also the Navigation Drawer - Live-Oproject ...

这也是Navigation Drawer - Live-O项目...

Navigation Drawer - Live-O

导航抽屉 - Live-O

The source code of the projectis available on GitHub.

项目源代码可在 GitHub 上找到。



The MaterialDrawer libraryaims to provide the easiest possible implementation of a navigation drawer for your application. It provides a great amount of out of the box customizations and also includes an easy to use header which can be used as AccountSwitcher.

MaterialDrawer库旨在提供最简便的实现导航抽屉您的应用程序。它提供了大量开箱即用的自定义设置,还包括一个易于使用的标头,可用作 AccountSwitcher。

MaterialDrawer library demo

MaterialDrawer 库演示



Please note that Android Studiomeanwhile has a template projectto create a Navigation Drawer Activityas shown in the screenshot.

请注意,Android Studio同时有一个模板项目来创建导航抽屉活动,如屏幕截图所示。

Navigation Drawer Activity

Navigation Drawer Activity

This repositorykeeps track of changes being made to the template.

存储库跟踪对模板所做的更改。

回答by Anshul Agarwal

I used below layout and able to achieve custom layout in Navigation View.

我使用了下面的布局并且能够在导航视图中实现自定义布局。

<android.support.design.widget.NavigationView
        android:id="@+id/navi_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start|top"
        android:background="@color/navigation_view_bg_color"
        app:theme="@style/NavDrawerTextStyle">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <include layout="@layout/drawer_header" />

            <include layout="@layout/navigation_drawer_menu" />
        </LinearLayout>
</android.support.design.widget.NavigationView> 

回答by Manuel Lopera

The easier solution for me was:

对我来说更简单的解决方案是:

Considerations:

注意事项:

  • This solution requires autogenerated Navigation Drawer Activity provided by Android Studio.
  • Classes DrawerItem, CustomDrawerAdapterand layout custom_drawer_item.xmlwere taken from this tutorial.
  • 此解决方案需要 Android Studio 提供的自动生成的 Navigation Drawer Activity。
  • DrawerItemCustomDrawerAdapter和布局custom_drawer_item.xml均取自本教程

1. Create this class for wrap the custom drawer item:

1. 创建此类用于包装自定义抽屉项目:

public class DrawerItem {

  String ItemName;
  int imgResID;

  public DrawerItem(String itemName, int imgResID) {
        super();
        ItemName = itemName;
        this.imgResID = imgResID;
  }

  public String getItemName() {
        return ItemName;
  }
  public void setItemName(String itemName) {
        ItemName = itemName;
  }
  public int getImgResID() {
        return imgResID;
  }
  public void setImgResID(int imgResID) {
        this.imgResID = imgResID;
  }
}

2. Create custom layout (custom_drawer_item.xml) for your drawer items:

2. 为您的抽屉项目创建自定义布局 (custom_drawer_item.xml):

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

<LinearLayout
    android:id="@+id/itemLayout"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:orientation="vertical"
    android:layout_marginTop="0dp"
    android:background="?android:attr/activatedBackgroundIndicator">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:minHeight="55dp">

        <ImageView
            android:id="@+id/drawer_icon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

        <TextView
            android:id="@+id/drawer_itemName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"/>
    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginBottom="1dp"
        android:layout_marginTop="1dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:background="#DADADC">
    </View>
</LinearLayout>
</RelativeLayout>

3. Create your custom adapter:

3. 创建您的自定义适配器:

import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CustomDrawerAdapter extends ArrayAdapter<DrawerItem> {

Context context;
List<DrawerItem> drawerItemList;
int layoutResID;

public CustomDrawerAdapter(Context context, int layoutResourceID, List<DrawerItem> listItems) {
    super(context, layoutResourceID, listItems);
    this.context = context;
    this.drawerItemList = listItems;
    this.layoutResID = layoutResourceID;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub

    DrawerItemHolder drawerHolder;
    View view = convertView;

    if (view == null) {
        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        drawerHolder = new DrawerItemHolder();

        view = inflater.inflate(layoutResID, parent, false);
        drawerHolder.ItemName = (TextView)view.findViewById(R.id.drawer_itemName);
        drawerHolder.icon = (ImageView) view.findViewById(R.id.drawer_icon);

        view.setTag(drawerHolder);

    } else {
        drawerHolder = (DrawerItemHolder) view.getTag();
    }

    DrawerItem dItem = (DrawerItem) this.drawerItemList.get(position);

    drawerHolder.icon.setImageDrawable(view.getResources().getDrawable(
            dItem.getImgResID()));
    drawerHolder.ItemName.setText(dItem.getItemName());

    return view;
}

private static class DrawerItemHolder {
    TextView ItemName;
    ImageView icon;
}
}

4. In autogenerated NavigationDrawerFragmentclass onCreateViewmethod, replace the autogenerated adapter for this:

4. 在自动生成的NavigationDrawerFragmentonCreateView方法中,为此替换自动生成的适配器:

ArrayList<DrawerItem> dataList = new ArrayList<DrawerItem>();
dataList.add(new DrawerItem(getString(R.string.title_section1), R.drawable.ic_action_1));
dataList.add(new DrawerItem(getString(R.string.title_section2), R.drawable.ic_action_2));
dataList.add(new DrawerItem(getString(R.string.title_section3), R.drawable.ic_action_3));

mDrawerListView.setAdapter(new CustomDrawerAdapter(
        getActivity(),
        R.layout.custom_drawer_item,
        dataList));

Remember replace R.string.title_sectionNand R.drawable.ic_action_Nfor your own resources.

记住替换R.string.title_sectionNR.drawable.ic_action_N为您自己的资源。

回答by amalBit

You can easily customize the android Navigation drawer once you know how its implemented. here is a nice tutorialwhere you can set it up.

一旦你知道它是如何实现的,你就可以轻松地自定义 android Navigation drawer。这是一个不错的教程,您可以在其中进行设置。

This will be the structure of your mainXML:

这将是您的 mainXML 的结构:

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

    <!-- Framelayout to display Fragments -->
    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <!-- Listview to display slider menu -->
    <ListView
        android:id="@+id/list_slidermenu"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="right"
        android:choiceMode="singleChoice"
        android:divider="@color/list_divider"
        android:dividerHeight="1dp"        
        android:listSelector="@drawable/list_selector"
        android:background="@color/list_background"/>
</android.support.v4.widget.DrawerLayout>

You can customize this listview to your liking by adding the header. And radiobuttons.

您可以通过添加标题来根据自己的喜好自定义此列表视图。和单选按钮。

回答by STS

Android Navigation Drawer using Activity I just followed the example :http://antonioleiva.com/navigation-view/

使用 Activity 的 Android Navigation Drawer 我只是按照示例操作:http: //antonioleiva.com/navigation-view/

You just need few Customization:

您只需要一些自定义:

public class MainActivity extends AppCompatActivity  {

public static final String AVATAR_URL = "http://lorempixel.com/200/200/people/1/";


private DrawerLayout drawerLayout;
private View content;
private Toolbar toolbar;
private NavigationView navigationView;
private ActionBarDrawerToggle drawerToggle;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dashboard);
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    initToolbar();
    setupDrawerLayout();

    content = findViewById(R.id.content);
    drawerToggle = setupDrawerToggle();
    final ImageView avatar = (ImageView) navigationView.getHeaderView(0).findViewById(R.id.avatar);
    Picasso.with(this).load(AVATAR_URL).transform(new CircleTransform()).into(avatar);


}


private void initToolbar() {
    final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    final ActionBar actionBar = getSupportActionBar();

    if (actionBar != null) {
        actionBar.setHomeAsUpIndicator(R.drawable.ic_menu_black_24dp);
        actionBar.setDisplayHomeAsUpEnabled(true);
    }
}
private ActionBarDrawerToggle setupDrawerToggle() {
    return new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open,  R.string.drawer_close);
}

   @Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    // Sync the toggle state after onRestoreInstanceState has occurred.
    drawerToggle.syncState();
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Pass any configuration change to the drawer toggles
    drawerToggle.onConfigurationChanged(newConfig);
}
 private void setupDrawerLayout() {

    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    navigationView = (NavigationView) findViewById(R.id.navigation_view);

    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {

            int id = menuItem.getItemId();

          switch (id) {
                case R.id.drawer_home:
                    Intent i = new Intent(getApplicationContext(), MainActivity.class);
                    startActivity(i);
                    finish();
                    break;
                case R.id.drawer_favorite:
                    Intent j = new Intent(getApplicationContext(), SecondActivity.class);
                    startActivity(j);
                    finish();
                    break;

            }


        return true;
    }
});

} Here is the xml Layout

这是xml布局

<android.support.v4.widget.DrawerLayout
android:id="@+id/drawer_layout"
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:fitsSystemWindows="true"
tools:context=".MainActivity">

<FrameLayout
    android:id="@+id/content"
    android:layout_width="match_parent"
    android:layout_height="match_parent">



    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBarLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <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/ThemeOverlay.AppCompat.Light"
            app:layout_scrollFlags="scroll|enterAlways|snap" />

    </android.support.design.widget.AppBarLayout>



</FrameLayout>

<android.support.design.widget.NavigationView
    android:id="@+id/navigation_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    app:headerLayout="@layout/drawer_header"
    app:menu="@menu/drawer"/>

Add drawer.xml in menu

在菜单中添加 drawer.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android">

<group
    android:checkableBehavior="single">

    <item
        android:id="@+id/drawer_home"
        android:checked="true"
        android:icon="@drawable/ic_home_black_24dp"
        android:title="@string/home"/>

    <item
        android:id="@+id/drawer_favourite"
        android:icon="@drawable/ic_favorite_black_24dp"
        android:title="@string/favourite"/>
    ...

    <item
        android:id="@+id/drawer_settings"
        android:icon="@drawable/ic_settings_black_24dp"
        android:title="@string/settings"/>

</group>

To open and close drawer add this values in string.xml

要打开和关闭抽屉,请在 string.xml 中添加此值

<string name="drawer_open">Open</string>
<string name="drawer_close">Close</string>

drawer.xml

抽屉文件

enter code here

<ImageView
    android:id="@+id/avatar"
    android:layout_width="64dp"
    android:layout_height="64dp"
    android:layout_margin="@dimen/spacing_large"
    android:elevation="4dp"
    tools:src="@drawable/ic_launcher"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/email"
    android:layout_marginLeft="@dimen/spacing_large"
    android:layout_marginStart="@dimen/spacing_large"
    android:text="Username"
    android:textAppearance="@style/TextAppearance.AppCompat.Body2"/>
<TextView
    android:id="@+id/email"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginLeft="@dimen/spacing_large"
    android:layout_marginStart="@dimen/spacing_large"
    android:layout_marginBottom="@dimen/spacing_large"
    android:text="[email protected]"
    android:textAppearance="@style/TextAppearance.AppCompat.Body1"/>

回答by Viswanath Lekshmanan

I need to add a header to categorize the list item in Drawer

我需要添加一个标题来对抽屉中的列表项进行分类

Customize the listViewor use expandableListView

自定义listView或使用expandableListView

I need a radio button to select some of my options

我需要一个单选按钮来选择我的一些选项

You can do that without modifying the current implementation of NavigationDrawer, You just need to create a custom adapter for your listView. You can add a parent layout as Drawerthen you can do any complex layouts within that as normal.

您可以在不修改 的当前实现的情况下做到这一点NavigationDrawer,您只需要为您的listView. 您可以添加父布局,Drawer然后您可以照常在其中执行任何复杂的布局。