Android APIs
public class

DrawerLayout

extends ViewGroup
java.lang.Object
   ↳ android.view.View
     ↳ android.view.ViewGroup
       ↳ android.support.v4.widget.DrawerLayout

Class Overview

DrawerLayout acts as a top-level container for window content that allows for interactive "drawer" views to be pulled out from the edge of the window.

Drawer positioning and layout is controlled using the android:layout_gravity attribute on child views corresponding to which side of the view you want the drawer to emerge from: left or right. (Or start/end on platform versions that support layout direction.)

To use a DrawerLayout, position your primary content view as the first child with a width and height of match_parent. Add drawers as child views after the main content view and set the layout_gravity appropriately. Drawers commonly use match_parent for height with a fixed width.

DrawerLayout.DrawerListener can be used to monitor the state and motion of drawer views. Avoid performing expensive operations such as layout during animation as it can cause stuttering; try to perform expensive operations during the STATE_IDLE state. DrawerLayout.SimpleDrawerListener offers default/no-op implementations of each callback method.

As per the Android Design guide, any drawers positioned to the left/start should always contain content for navigating around the application, whereas any drawers positioned to the right/end should always contain actions to take on the current content. This preserves the same navigation left, actions right structure present in the Action Bar and elsewhere.

Summary

Nested Classes
interface DrawerLayout.DrawerListener Listener for monitoring events about drawers. 
class DrawerLayout.LayoutParams  
class DrawerLayout.SavedState State persisted across instances  
class DrawerLayout.SimpleDrawerListener Stub/no-op implementations of all methods of DrawerLayout.DrawerListener
[Expand]
Inherited XML Attributes
From class android.view.ViewGroup
From class android.view.View
Constants
int LOCK_MODE_LOCKED_CLOSED The drawer is locked closed.
int LOCK_MODE_LOCKED_OPEN The drawer is locked open.
int LOCK_MODE_UNLOCKED The drawer is unlocked.
int STATE_DRAGGING Indicates that a drawer is currently being dragged by the user.
int STATE_IDLE Indicates that any drawers are in an idle, settled state.
int STATE_SETTLING Indicates that a drawer is in the process of settling to a final position.
[Expand]
Inherited Constants
From class android.view.ViewGroup
From class android.view.View
[Expand]
Inherited Fields
From class android.view.View
Public Constructors
DrawerLayout(Context context)
DrawerLayout(Context context, AttributeSet attrs)
DrawerLayout(Context context, AttributeSet attrs, int defStyle)
Public Methods
void addView(View child, int index, ViewGroup.LayoutParams params)
Adds a child view with the specified layout parameters.
void closeDrawer(View drawerView)
Close the specified drawer view by animating it into view.
void closeDrawer(int gravity)
Close the specified drawer by animating it out of view.
void closeDrawers()
Close all currently open drawer views by animating them out of view.
void computeScroll()
Called by a parent to request that a child update its values for mScrollX and mScrollY if necessary.
ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs)
Returns a new set of layout parameters based on the supplied attributes set.
int getDrawerLockMode(int edgeGravity)
Check the lock mode of the drawer with the given gravity.
int getDrawerLockMode(View drawerView)
Check the lock mode of the given drawer view.
CharSequence getDrawerTitle(int edgeGravity)
Returns the title of the drawer with the given gravity.
boolean isDrawerOpen(View drawer)
Check if the given drawer view is currently in an open state.
boolean isDrawerOpen(int drawerGravity)
Check if the given drawer view is currently in an open state.
boolean isDrawerVisible(int drawerGravity)
Check if a given drawer view is currently visible on-screen.
boolean isDrawerVisible(View drawer)
Check if a given drawer view is currently visible on-screen.
boolean onInterceptTouchEvent(MotionEvent ev)
Implement this method to intercept all touch screen motion events.
boolean onKeyDown(int keyCode, KeyEvent event)
Default implementation of KeyEvent.Callback.onKeyDown(): perform press of the view when KEYCODE_DPAD_CENTER or KEYCODE_ENTER is released, if the view is enabled and clickable.
boolean onKeyUp(int keyCode, KeyEvent event)
Default implementation of KeyEvent.Callback.onKeyUp(): perform clicking of the view when KEYCODE_DPAD_CENTER or KEYCODE_ENTER is released.
boolean onTouchEvent(MotionEvent ev)
Implement this method to handle touch screen motion events.
void openDrawer(int gravity)
Open the specified drawer by animating it out of view.
void openDrawer(View drawerView)
Open the specified drawer view by animating it into view.
void requestDisallowInterceptTouchEvent(boolean disallowIntercept)
Called when a child does not want this parent and its ancestors to intercept touch events with onInterceptTouchEvent(MotionEvent).
void requestLayout()
Call this when something has changed which has invalidated the layout of this view.
void setDrawerListener(DrawerLayout.DrawerListener listener)
Set a listener to be notified of drawer events.
void setDrawerLockMode(int lockMode, int edgeGravity)
Enable or disable interaction with the given drawer.
void setDrawerLockMode(int lockMode, View drawerView)
Enable or disable interaction with the given drawer.
void setDrawerLockMode(int lockMode)
Enable or disable interaction with all drawers.
void setDrawerShadow(int resId, int gravity)
Set a simple drawable used for the left or right shadow.
void setDrawerShadow(Drawable shadowDrawable, int gravity)
Set a simple drawable used for the left or right shadow.
void setDrawerTitle(int edgeGravity, CharSequence title)
Sets the title of the drawer with the given gravity.
void setScrimColor(int color)
Set a color to use for the scrim that obscures primary content while a drawer is open.
Protected Methods
boolean checkLayoutParams(ViewGroup.LayoutParams p)
boolean drawChild(Canvas canvas, View child, long drawingTime)
Draw one child of this View Group.
ViewGroup.LayoutParams generateDefaultLayoutParams()
Returns a set of default layout parameters.
ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p)
Returns a safe set of layout parameters based on the supplied layout params.
void onAttachedToWindow()
This is called when the view is attached to a window.
void onDetachedFromWindow()
This is called when the view is detached from a window.
void onLayout(boolean changed, int l, int t, int r, int b)
Called from layout when this view should assign a size and position to each of its children.
void onMeasure(int widthMeasureSpec, int heightMeasureSpec)

Measure the view and its content to determine the measured width and the measured height.

void onRestoreInstanceState(Parcelable state)
Hook allowing a view to re-apply a representation of its internal state that had previously been generated by onSaveInstanceState().
Parcelable onSaveInstanceState()
Hook allowing a view to generate a representation of its internal state that can later be used to create a new instance with that same state.
[Expand]
Inherited Methods
From class android.view.ViewGroup
From class android.view.View
From class java.lang.Object
From interface android.graphics.drawable.Drawable.Callback
From interface android.view.KeyEvent.Callback
From interface android.view.ViewManager
From interface android.view.ViewParent
From interface android.view.accessibility.AccessibilityEventSource

Constants

public static final int LOCK_MODE_LOCKED_CLOSED

The drawer is locked closed. The user may not open it, though the app may open it programmatically.

Constant Value: 1 (0x00000001)

public static final int LOCK_MODE_LOCKED_OPEN

The drawer is locked open. The user may not close it, though the app may close it programmatically.

Constant Value: 2 (0x00000002)

public static final int LOCK_MODE_UNLOCKED

The drawer is unlocked.

Constant Value: 0 (0x00000000)

public static final int STATE_DRAGGING

Indicates that a drawer is currently being dragged by the user.

Constant Value: 1 (0x00000001)

public static final int STATE_IDLE

Indicates that any drawers are in an idle, settled state. No animation is in progress.

Constant Value: 0 (0x00000000)

public static final int STATE_SETTLING

Indicates that a drawer is in the process of settling to a final position.

Constant Value: 2 (0x00000002)

Public Constructors

public DrawerLayout (Context context)

public DrawerLayout (Context context, AttributeSet attrs)

public DrawerLayout (Context context, AttributeSet attrs, int defStyle)

Public Methods

public void addView (View child, int index, ViewGroup.LayoutParams params)

Adds a child view with the specified layout parameters.

Note: do not invoke this method from draw(android.graphics.Canvas), onDraw(android.graphics.Canvas), dispatchDraw(android.graphics.Canvas) or any related method.

Parameters
child the child view to add
index the position at which to add the child
params the layout parameters to set on the child

public void closeDrawer (View drawerView)

Close the specified drawer view by animating it into view.

Parameters
drawerView Drawer view to close

public void closeDrawer (int gravity)

Close the specified drawer by animating it out of view.

Parameters
gravity Gravity.LEFT to move the left drawer or Gravity.RIGHT for the right. GravityCompat.START or GravityCompat.END may also be used.

public void closeDrawers ()

Close all currently open drawer views by animating them out of view.

public void computeScroll ()

Called by a parent to request that a child update its values for mScrollX and mScrollY if necessary. This will typically be done if the child is animating a scroll using a Scroller object.

public ViewGroup.LayoutParams generateLayoutParams (AttributeSet attrs)

Returns a new set of layout parameters based on the supplied attributes set.

Parameters
attrs the attributes to build the layout parameters from
Returns

public int getDrawerLockMode (int edgeGravity)

Check the lock mode of the drawer with the given gravity.

Parameters
edgeGravity Gravity of the drawer to check

public int getDrawerLockMode (View drawerView)

Check the lock mode of the given drawer view.

Parameters
drawerView Drawer view to check lock mode

public CharSequence getDrawerTitle (int edgeGravity)

Returns the title of the drawer with the given gravity.

Parameters
edgeGravity Gravity.LEFT, RIGHT, START or END. Expresses which drawer to return the title for.
Returns
  • The title of the drawer, or null if none set.

public boolean isDrawerOpen (View drawer)

Check if the given drawer view is currently in an open state. To be considered "open" the drawer must have settled into its fully visible state. To check for partial visibility use isDrawerVisible(android.view.View).

Parameters
drawer Drawer view to check
Returns
  • true if the given drawer view is in an open state

public boolean isDrawerOpen (int drawerGravity)

Check if the given drawer view is currently in an open state. To be considered "open" the drawer must have settled into its fully visible state. If there is no drawer with the given gravity this method will return false.

Parameters
drawerGravity Gravity of the drawer to check
Returns
  • true if the given drawer view is in an open state

public boolean isDrawerVisible (int drawerGravity)

Check if a given drawer view is currently visible on-screen. The drawer may be only peeking onto the screen, fully extended, or anywhere in between. If there is no drawer with the given gravity this method will return false.

Parameters
drawerGravity Gravity of the drawer to check
Returns
  • true if the given drawer is visible on-screen

public boolean isDrawerVisible (View drawer)

Check if a given drawer view is currently visible on-screen. The drawer may be only peeking onto the screen, fully extended, or anywhere inbetween.

Parameters
drawer Drawer view to check
Returns
  • true if the given drawer is visible on-screen

public boolean onInterceptTouchEvent (MotionEvent ev)

Implement this method to intercept all touch screen motion events. This allows you to watch events as they are dispatched to your children, and take ownership of the current gesture at any point.

Using this function takes some care, as it has a fairly complicated interaction with View.onTouchEvent(MotionEvent), and using it requires implementing that method as well as this one in the correct way. Events will be received in the following order:

  1. You will receive the down event here.
  2. The down event will be handled either by a child of this view group, or given to your own onTouchEvent() method to handle; this means you should implement onTouchEvent() to return true, so you will continue to see the rest of the gesture (instead of looking for a parent view to handle it). Also, by returning true from onTouchEvent(), you will not receive any following events in onInterceptTouchEvent() and all touch processing must happen in onTouchEvent() like normal.
  3. For as long as you return false from this function, each following event (up to and including the final up) will be delivered first here and then to the target's onTouchEvent().
  4. If you return true from here, you will not receive any following events: the target view will receive the same event but with the action ACTION_CANCEL, and all further events will be delivered to your onTouchEvent() method and no longer appear here.

Parameters
ev The motion event being dispatched down the hierarchy.
Returns
  • Return true to steal motion events from the children and have them dispatched to this ViewGroup through onTouchEvent(). The current target will receive an ACTION_CANCEL event, and no further messages will be delivered here.

public boolean onKeyDown (int keyCode, KeyEvent event)

Default implementation of KeyEvent.Callback.onKeyDown(): perform press of the view when KEYCODE_DPAD_CENTER or KEYCODE_ENTER is released, if the view is enabled and clickable.

Key presses in software keyboards will generally NOT trigger this listener, although some may elect to do so in some situations. Do not rely on this to catch software key presses.

Parameters
keyCode A key code that represents the button pressed, from KeyEvent.
event The KeyEvent object that defines the button action.
Returns
  • If you handled the event, return true. If you want to allow the event to be handled by the next receiver, return false.

public boolean onKeyUp (int keyCode, KeyEvent event)

Default implementation of KeyEvent.Callback.onKeyUp(): perform clicking of the view when KEYCODE_DPAD_CENTER or KEYCODE_ENTER is released.

Key presses in software keyboards will generally NOT trigger this listener, although some may elect to do so in some situations. Do not rely on this to catch software key presses.

Parameters
keyCode A key code that represents the button pressed, from KeyEvent.
event The KeyEvent object that defines the button action.
Returns
  • If you handled the event, return true. If you want to allow the event to be handled by the next receiver, return false.

public boolean onTouchEvent (MotionEvent ev)

Implement this method to handle touch screen motion events.

If this method is used to detect click actions, it is recommended that the actions be performed by implementing and calling performClick(). This will ensure consistent system behavior, including:

  • obeying click sound preferences
  • dispatching OnClickListener calls
  • handling ACTION_CLICK when accessibility features are enabled

Parameters
ev The motion event.
Returns
  • True if the event was handled, false otherwise.

public void openDrawer (int gravity)

Open the specified drawer by animating it out of view.

Parameters
gravity Gravity.LEFT to move the left drawer or Gravity.RIGHT for the right. GravityCompat.START or GravityCompat.END may also be used.

public void openDrawer (View drawerView)

Open the specified drawer view by animating it into view.

Parameters
drawerView Drawer view to open

public void requestDisallowInterceptTouchEvent (boolean disallowIntercept)

Called when a child does not want this parent and its ancestors to intercept touch events with onInterceptTouchEvent(MotionEvent).

This parent should pass this call onto its parents. This parent must obey this request for the duration of the touch (that is, only clear the flag after this parent has received an up or a cancel.

Parameters
disallowIntercept True if the child does not want the parent to intercept touch events.

public void requestLayout ()

Call this when something has changed which has invalidated the layout of this view. This will schedule a layout pass of the view tree. This should not be called while the view hierarchy is currently in a layout pass (isInLayout(). If layout is happening, the request may be honored at the end of the current layout pass (and then layout will run again) or after the current frame is drawn and the next layout occurs.

Subclasses which override this method should call the superclass method to handle possible request-during-layout errors correctly.

public void setDrawerListener (DrawerLayout.DrawerListener listener)

Set a listener to be notified of drawer events.

Parameters
listener Listener to notify when drawer events occur

public void setDrawerLockMode (int lockMode, int edgeGravity)

Enable or disable interaction with the given drawer.

This allows the application to restrict the user's ability to open or close the given drawer. DrawerLayout will still respond to calls to openDrawer(int), closeDrawer(int) and friends if a drawer is locked.

Locking a drawer open or closed will implicitly open or close that drawer as appropriate.

Parameters
lockMode The new lock mode for the given drawer. One of LOCK_MODE_UNLOCKED, LOCK_MODE_LOCKED_CLOSED or LOCK_MODE_LOCKED_OPEN.
edgeGravity Gravity.LEFT, RIGHT, START or END. Expresses which drawer to change the mode for.

public void setDrawerLockMode (int lockMode, View drawerView)

Enable or disable interaction with the given drawer.

This allows the application to restrict the user's ability to open or close the given drawer. DrawerLayout will still respond to calls to openDrawer(int), closeDrawer(int) and friends if a drawer is locked.

Locking a drawer open or closed will implicitly open or close that drawer as appropriate.

Parameters
lockMode The new lock mode for the given drawer. One of LOCK_MODE_UNLOCKED, LOCK_MODE_LOCKED_CLOSED or LOCK_MODE_LOCKED_OPEN.
drawerView The drawer view to change the lock mode for

public void setDrawerLockMode (int lockMode)

Enable or disable interaction with all drawers.

This allows the application to restrict the user's ability to open or close any drawer within this layout. DrawerLayout will still respond to calls to openDrawer(int), closeDrawer(int) and friends if a drawer is locked.

Locking drawers open or closed will implicitly open or close any drawers as appropriate.

Parameters
lockMode The new lock mode for the given drawer. One of LOCK_MODE_UNLOCKED, LOCK_MODE_LOCKED_CLOSED or LOCK_MODE_LOCKED_OPEN.

public void setDrawerShadow (int resId, int gravity)

Set a simple drawable used for the left or right shadow. The drawable provided must have a nonzero intrinsic width.

Parameters
resId Resource id of a shadow drawable to use at the edge of a drawer
gravity Which drawer the shadow should apply to

public void setDrawerShadow (Drawable shadowDrawable, int gravity)

Set a simple drawable used for the left or right shadow. The drawable provided must have a nonzero intrinsic width.

Parameters
shadowDrawable Shadow drawable to use at the edge of a drawer
gravity Which drawer the shadow should apply to

public void setDrawerTitle (int edgeGravity, CharSequence title)

Sets the title of the drawer with the given gravity.

When accessibility is turned on, this is the title that will be used to identify the drawer to the active accessibility service.

Parameters
edgeGravity Gravity.LEFT, RIGHT, START or END. Expresses which drawer to set the title for.
title The title for the drawer.

public void setScrimColor (int color)

Set a color to use for the scrim that obscures primary content while a drawer is open.

Parameters
color Color to use in 0xAARRGGBB format.

Protected Methods

protected boolean checkLayoutParams (ViewGroup.LayoutParams p)

protected boolean drawChild (Canvas canvas, View child, long drawingTime)

Draw one child of this View Group. This method is responsible for getting the canvas in the right state. This includes clipping, translating so that the child's scrolled origin is at 0, 0, and applying any animation transformations.

Parameters
canvas The canvas on which to draw the child
child Who to draw
drawingTime The time at which draw is occurring
Returns
  • True if an invalidate() was issued

protected ViewGroup.LayoutParams generateDefaultLayoutParams ()

Returns a set of default layout parameters. These parameters are requested when the View passed to addView(View) has no layout parameters already set. If null is returned, an exception is thrown from addView.

Returns
  • a set of default layout parameters or null

protected ViewGroup.LayoutParams generateLayoutParams (ViewGroup.LayoutParams p)

Returns a safe set of layout parameters based on the supplied layout params. When a ViewGroup is passed a View whose layout params do not pass the test of checkLayoutParams(android.view.ViewGroup.LayoutParams), this method is invoked. This method should return a new set of layout params suitable for this ViewGroup, possibly by copying the appropriate attributes from the specified set of layout params.

Parameters
p The layout parameters to convert into a suitable set of layout parameters for this ViewGroup.
Returns

protected void onAttachedToWindow ()

This is called when the view is attached to a window. At this point it has a Surface and will start drawing. Note that this function is guaranteed to be called before onDraw(android.graphics.Canvas), however it may be called any time before the first onDraw -- including before or after onMeasure(int, int).

protected void onDetachedFromWindow ()

This is called when the view is detached from a window. At this point it no longer has a surface for drawing.

protected void onLayout (boolean changed, int l, int t, int r, int b)

Called from layout when this view should assign a size and position to each of its children. Derived classes with children should override this method and call layout on each of their children.

Parameters
changed This is a new size or position for this view
l Left position, relative to parent
t Top position, relative to parent
r Right position, relative to parent
b Bottom position, relative to parent

protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec)

Measure the view and its content to determine the measured width and the measured height. This method is invoked by measure(int, int) and should be overriden by subclasses to provide accurate and efficient measurement of their contents.

CONTRACT: When overriding this method, you must call setMeasuredDimension(int, int) to store the measured width and height of this view. Failure to do so will trigger an IllegalStateException, thrown by measure(int, int). Calling the superclass' onMeasure(int, int) is a valid use.

The base class implementation of measure defaults to the background size, unless a larger size is allowed by the MeasureSpec. Subclasses should override onMeasure(int, int) to provide better measurements of their content.

If this method is overridden, it is the subclass's responsibility to make sure the measured height and width are at least the view's minimum height and width (getSuggestedMinimumHeight() and getSuggestedMinimumWidth()).

Parameters
widthMeasureSpec horizontal space requirements as imposed by the parent. The requirements are encoded with View.MeasureSpec.
heightMeasureSpec vertical space requirements as imposed by the parent. The requirements are encoded with View.MeasureSpec.

protected void onRestoreInstanceState (Parcelable state)

Hook allowing a view to re-apply a representation of its internal state that had previously been generated by onSaveInstanceState(). This function will never be called with a null state.

Parameters
state The frozen state that had previously been returned by onSaveInstanceState().

protected Parcelable onSaveInstanceState ()

Hook allowing a view to generate a representation of its internal state that can later be used to create a new instance with that same state. This state should only contain information that is not persistent or can not be reconstructed later. For example, you will never store your current position on screen because that will be computed again when a new instance of the view is placed in its view hierarchy.

Some examples of things you may store here: the current cursor position in a text view (but usually not the text itself since that is stored in a content provider or other persistent storage), the currently selected item in a list view.

Returns
  • Returns a Parcelable object containing the view's current dynamic state, or null if there is nothing interesting to save. The default implementation returns null.