Create navigation drawer → creating a navigation drawer

Source: Internet
Author: User

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

Create drawer navigation

The navigation drawer is in
The application main navigation option panel at the left edge of the screen. it is hidden most of the time, but it is displayed when you slide from the left side of the screen with your fingers, or when you click the application icon on the toolbar at the top of the application.

This course describes how to effectively use the drawlayout interface in the support library to implement a navigation drawer.

Create a drawer Layout

Add a drawer. When declaring the UI, use drawlayout as the root view of your layout file ). in drawlayout, add a view of the main content (your main layout file when the drawer navigation is hidden) and another view containing the navigation drawer.

For example, the following layout uses drawlayout, which has two subviews: A framelayout contains the main content and a navigation drawer of the listview.

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

This layout file demonstrates some important Layout features.

  • The view of the main content (framelayout) must be the first child element of drawlayout, because the navigation drawer is above the main content view.
  • The main content view is set to match the width and height of the parent view, because it indicates that the navigation drawer of the entire interface is hidden.
  • The horizontal gravity and Android: layout_gravity attributes of the drawer view (listview) must be specified. Supports the right-to-left (RTL) language."start"Replace"left"(So the drawer appears on the right side of the layout when the layout is RTL ).
  • The drawer view specifies that its width matches the parent view with the DP unit and height. The drawer width cannot exceed 320 DP, so you can always see part of the main content view.
Initialize drawer list

In your activity, the first thing is to initialize the elements in the navigation drawer list. How you do it depends on the content of your application, but a navigation drawer usually includes a listview, therefore, the list should be filled by an adapter (for example, arrayadapter or simplecursoradapter ).

For example, here we demonstrate how to use string array to initialize a navigation list.

public class MainActivity extends Activity {    private String[] mPlanetTitles;    private ListView mDrawerList;    ...    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        mPlanetTitles = getResources().getStringArray(R.array.planets_array);        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());        ...    }}

This Code calls setonitemclicklistener () to receive click events in the navigation drawer list. The next section shows how to implement this interface and change the content view when you select an item.

Handling navigation click events

When you select an item in the drawer list, the system calls onitemclick () on onitemclicklistener to setonitemclicklistener ().

What do you do in the onitemclick () method,
Depending on the structure of your app implementation. In the following example, selecting each item will insert a different fragment in the layout of the main content.

private 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    mDrawer.setItemChecked(position, true);    setTitle(mPlanetTitles[position]);    mDrawerLayout.closeDrawer(mDrawer);}@Overridepublic void setTitle(CharSequence title) {    mTitle = title;    getActionBar().setTitle(mTitle);}

Listen to open and close events

Listen for opening and closing events in the drawer, call your drawerlayout setdrawerlistener (), and pass it to drawerlayout. implementation of drawerlistener. this interface provides callback drawer events, such as ondraweropened () and ondrawerclosed ().

However, compared with the implementation of drawerlayout. drawerlistener, if your activity includes a toolbar, You can inherit the actionbardrawertoggle class. actionbardrawertoggle implements drawerlayout. drawerlistener.
So you can still override these callbacks, but it also helps with the correct interaction behavior between the toolbar icon and the navigation drawer (which will be further discussed in the next section ).

Just like in the navigation drawer Design Guide, when the drawer is visible, you should modify the toolbar content,
For example, changing the title and deleting the item. The following code uses an instance of the actionbardrawertoggle class to show how to override the callback method of drawerlayout. drawerlistener:

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) {                getActionBar().setTitle(mTitle);                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()            }            /** Called when a drawer has settled in a completely open state. */            public void onDrawerOpened(View 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);    }}

The next section describes the actionbardrawertoggle constructor parameters and other required steps to set them to process the toolbar icons.

Open the close application icon

Users can open and close the navigation drawer and slide from the left edge of the screen by fingers, but if you use the toolbar, you should also allow users to open and close it by touching the app icon. the application icon can also display a Special icon about the navigation drawer status.
You can implement all these actions by using actionbardrawertoggle, as shown in the previous section.

Let actionbardrawertoggle work and create an instance using its constructor. This requires the following parameters:

  • Activity holding the drawer.
  • Drawerlayout object.
  • A drawable resource serves as a drawer indicator.
  • String Resource Description "open drawer" action.
  • String Resource Description "Close drawer" action.

Then, whether or not you have created an actionbardrawertoggle subclass as the listener of your drawer, you need to call your actionbardrawertoggle in several activity lifecycles:

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) {                getActionBar().setTitle(mTitle);            }            /** Called when a drawer has settled in a completely open state. */            public void onDrawerOpened(View 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);    }    ...}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.