Android 开发之Navigation Drawer

Posted zhenjie_chang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android 开发之Navigation Drawer相关的知识,希望对你有一定的参考价值。

侧滑菜单在android应用中应用很常见,Android 的API中提供了侧滑菜单,我们可以很方便的将他应用在我们的项目中。

那么如何创建一个侧滑菜单呢?

创建<DrawerLayout>布局

在项目的用户界面的xml布局文件中使用<DrawerLayout>标签,<DrawerLayout>标签必须为xml的根标签。在<DrawerLayout>标签中只能放置两个元素,其中一个放置界面的主要内容,另一个用来放置侧滑菜单。

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

如上面的布局,drawerlayout有两个子视图,一个FrameLayout用于放置主要的内容,另一个ListView用于放置侧滑菜单。

注意:内容布局必须放在第一个,因为在Z轴上,侧滑菜单应该位于内容之上

         内容布局的宽和高必须match_parent填满父容器

         侧滑菜单必须使用android:layout_gravity=“start”属性来指定它的水平gravity值

         侧滑菜单高度应该填充满父容器,宽度使用dp值,且不能大于320dp

初始化侧滑菜单列表

侧滑菜单的条目根据应用的内容而定,但是侧滑菜单一般使用ListView存放菜单条目,初始化侧滑菜单和ListView的使用相似,注册ItemClick事件来出来菜单的点击事件。

public class MainActivity extends Activity 
    private String[] mPlanetTitles;
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    ...

    @Override
    public void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mPlanetTitles = getResources().getStringArray(R.array.planets_array);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        // Set the adapter for the list view
        mDrawerList.setAdapter(new ArrayAdapter<String>(this,
                R.layout.drawer_list_item, mPlanetTitles));
        // Set the list's click listener
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        ...
    
处理菜单点击事件
点击菜单选项的时候,系统会调用onItemClickListener接口的onItemClick()事件,具体处理逻辑要根据自己的应用内容而定,下面事例中点击不同的菜单,在content中切换不同的Fragment.

rivate class DrawerItemClickListener implements ListView.OnItemClickListener 
    @Override
    public void onItemClick(AdapterView parent, View view, int position, long id) 
        selectItem(position);
    


/** Swaps fragments in the main content view */
private void selectItem(int position) 
    // Create a new fragment and specify the planet to show based on position
    Fragment fragment = new PlanetFragment();
    Bundle args = new Bundle();
    args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
    fragment.setArguments(args);

    // Insert the fragment by replacing any existing fragment
    FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.beginTransaction()
                   .replace(R.id.content_frame, fragment)
                   .commit();

    // Highlight the selected item, update the title, and close the drawer
    mDrawerList.setItemChecked(position, true);
    setTitle(mPlanetTitles[position]);
    mDrawerLayout.closeDrawer(mDrawerList);


@Override
public void setTitle(CharSequence title) 
    mTitle = title;
    getActionBar().setTitle(mTitle);


监听菜单打开和关闭的事件  

开发的时候经常需要知道侧滑菜单是否处于打开状态,这就需要调用setDrawerListener()来注册DrawerLayout的监听事件,同其他注册监听事件一样,在注册的时候传入DrawerListener的实例

DrawerListener的实现如下:

DrawerLayout.DrawerListener d=new DrawerLayout.DrawerListener() 

        @Override
        public void onDrawerStateChanged(int arg0) 
            // TODO Auto-generated method stub

        

        @Override
        public void onDrawerSlide(View arg0, float arg1) 
            // TODO 菜单滑动的时候

        

        @Override
        public void onDrawerOpened(View arg0) 
            // TODO 侧滑菜单打开

        

        @Override
        public void onDrawerClosed(View arg0) 
            // TODO 侧滑菜单关闭

        
    ;

当侧滑菜单打开关闭或者滑动的时候会调用相应的回调方法

当应用中使用了ActionBar之后,我们可以直接继承 ActionBarDrawerToggle 类,因为ActionBarDrawerToogle类已经实现了DrawerListener接口, 如果想

要实现自己特定逻辑我们还是可以重写接口的方法。以下是使用ActionBarDrawerToogle类的实现方式

public class MainActivity extends Activity 
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mDrawerToggle;
    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
    ...

    @Override
    public void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ...

        mTitle = mDrawerTitle = getTitle();
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) 

            /** Called when a drawer has settled in a completely closed state. */
            public void onDrawerClosed(View view) 
                super.onDrawerClosed(view);
                getActionBar().setTitle(mTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            

            /** Called when a drawer has settled in a completely open state. */
            public void onDrawerOpened(View drawerView) 
                super.onDrawerOpened(drawerView);
                getActionBar().setTitle(mDrawerTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            
        ;

        // Set the drawer toggle as the DrawerListener
        mDrawerLayout.setDrawerListener(mDrawerToggle);
    

    /* Called whenever we call invalidateOptionsMenu() */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) 
        // If the nav drawer is open, hide action items related to the content view
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    


点击应用图标打开或者关闭菜单

在使用侧滑菜单的时候,可以在屏幕左侧滑动打开菜单,同时我们也可以点击ActionBar的应用图标来打开侧滑菜单。


首先我们要创建ActionBarDrawerToogle类的实例。并且在Activity的生命周期的一些方法中调用该类的方法。


public class MainActivity extends Activity 
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mDrawerToggle;
    ...

    public void onCreate(Bundle savedInstanceState) 
        ...

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerToggle = new ActionBarDrawerToggle(
                this,                  /* host Activity */
                mDrawerLayout,         /* DrawerLayout object */
                R.drawable.ic_drawer,  /* nav drawer icon to replace 'Up' caret */
                R.string.drawer_open,  /* "open drawer" description */
                R.string.drawer_close  /* "close drawer" description */
                ) 

            /** Called when a drawer has settled in a completely closed state. */
            public void onDrawerClosed(View view) 
                super.onDrawerClosed(view);
                getActionBar().setTitle(mTitle);
            

            /** Called when a drawer has settled in a completely open state. */
            public void onDrawerOpened(View drawerView) 
                super.onDrawerOpened(drawerView);
                getActionBar().setTitle(mDrawerTitle);
            
        ;

        // Set the drawer toggle as the DrawerListener
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);
    

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

    @Override
    public void onConfigurationChanged(Configuration newConfig) 
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    

    @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);
    

    ...

以上是关于Android 开发之Navigation Drawer的主要内容,如果未能解决你的问题,请参考以下文章

Android jetpack之Navigation

Android开发 navigation的跳转动画实现

Android:安卓学习笔记之navigation的简单理解和使用

Android:安卓学习笔记之navigation的简单理解和使用

Android:安卓学习笔记之navigation的简单理解和使用

Android Studio3.3 之 Navigation Editor 详解