Android drawerlayout Drawer Effect

Source: Internet
Author: User

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

Official Website Example: Navigationdrawer.zip

Android.support.v4.widget.DrawerLayout drawer layout. The widget can only implement left-to-right, right-to-left

Opendrawer (), Closedrawer (), Isdraweropen ()


The main layout files and activity implementations of the example are posted below

Activity_main.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" > <FrameLayou T android:id= "@+id/content_frame" android:layout_width= "match_parent" android:layout_height= "Match_pa Rent "/> <listview android:id=" @+id/left_drawer "android:layout_width=" 240DP "android:layout _height= "Match_parent" android:layout_gravity= "right" android:choicemode= "Singlechoice" Android:divid Er= "@android: Color/transparent" android:dividerheight= "0DP" android:background= "#111"/> <!--an    Droid:choicemode checked state with ItemClick no conflict none value is 0, indicates no selection mode, Singlechoice value is 1, indicates that one item can be selected; multiplechoice A value of 2 indicates that multiple items can be selected. Android:layout_gravityleft right<span style= "White-space:pre" ></span>left or start right or End<span Style= "White-space:pRe "></span>start end indicates whether the effect in the drawer appears from left to right or right to left--></android.support.v4.widget.drawerlayout> 

Package com.stone.drawerlayout;/* * Copyright the Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * You are not a use this file except in compliance with the License. * Obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * unless required by applic Able law or agreed to in writing, software * Distributed under the License are distributed on a "as is" BASIS, * without W Arranties or CONDITIONS of any KIND, either express OR implied. * See the License for the specific language governing permissions and * limitations under the License. */import Java.util.locale;import Android.app.activity;import Android.app.fragment;import Android.app.fragmentmanager;import Android.app.searchmanager;import Android.content.intent;import Android.content.res.configuration;import Android.os.bundle;import Android.support.v4.app.ActionBarDrawerToggle; Import Android.support.v4.view.gravitycompat;import Android.support.v4.wiDget. Drawerlayout;import Android.view.layoutinflater;import Android.view.menu;import Android.view.MenuInflater;import Android.view.menuitem;import Android.view.view;import Android.view.viewgroup;import Android.widget.AdapterView; Import Android.widget.arrayadapter;import Android.widget.imageview;import Android.widget.listview;import android.widget.toast;/** * This example illustrates a common usage of the drawerlayout widgets * in the Android support Lib Rary. * <p/> * <p>when a navigation (left) drawer is present, the host activity should detect presses of * the Actio N Bar s up affordance as a signal to open and close the navigation drawer. The * Actionbardrawertoggle facilitates this behavior. * Items within the drawer should fall into one of both categories:</p> * <p/> * <ul> * <li><stro Ng>view Switches</strong>.  A View switch follows the same basic policies as * List or tab navigation in that a view switch does not create navigation HistoRy. * This pattern should is used at the root activity of a task, leaving some form * of-Navigation active for ACT Ivities further down the navigation hierarchy.</li> * <li><strong>selective up</strong>. The drawer allows the user to choose a alternate * parent for up navigation. This allows a user-to-jump across an app's navigation * hierarchy at'll. The application should treat this as it treats up navigation from * a different task, replacing the current task stack usi ng Taskstackbuilder or similar. * This is the only form of navigation drawer that should be used outside of the root * activity of a task.</li> * &L t;/ul> * <p/> * <p>right side drawers should is used for the actions, not navigation. This follows the pattern * established by the Action Bar that navigation should is to the left and the actions to the right. * An action should is an operation performed on the current contents of the window, * For example enabling or DisablinG A data overlay on top of the Content.</p> */public class Mainactivity extends Activity {private Drawer    Layout mdrawerlayout;    Private ListView mdrawerlist;    Private Actionbardrawertoggle Mdrawertoggle;    Private Charsequence Mdrawertitle;    Private Charsequence Mtitle;    Private string[] mplanettitles;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Mtitle = Mdrawertitle = GetTitle ();        Mplanettitles = Getresources (). Getstringarray (R.array.planets_array);        Mdrawerlayout = (drawerlayout) Findviewbyid (r.id.drawer_layout); Mdrawerlist = (ListView) Findviewbyid (r.id.left_drawer);//Drawer view//Set a custom shadow that overlays the main co         Ntent when the drawer opens Mdrawerlayout.setdrawershadow (R.drawable.drawer_shadow, Gravitycompat.start);//Set Shadow Set up the drawer ' s list view with items and click ListenEr mdrawerlist.setadapter (New arrayadapter<string> (this, R.layout.drawer_list_item, mplanettit        Les));        Mdrawerlist.setonitemclicklistener (New Draweritemclicklistener ()); The Enable ActionBar app icon to behave as action to toggle NAV drawer requires an API level of Getactionbar (). Setdisplayhom Easupenabled (TRUE);//Add a return icon to the left of Home icon Getactionbar (). Sethomebuttonenabled (True); Requires API level 14 to use Home-icon to click//Actionbardrawertoggle ties together the the proper interactions//BETW Een the sliding drawer and the Action Bar app icon Mdrawertoggle = new Actionbardrawertoggle (the drawer on//V4 control Actionbar opens Off this,/* host Activity */mdrawerlayout,/* Drawerlayout Object * /r.drawable.ic_drawer,/* NAV drawer image to replace ' up ' caret *///icon return icon R.STRING.D Rawer_open,/* "Open drawer" description for accessibility */r.string. Drawer_close/* "Close drawer" description for accessibility */) {public void ondrawerclosed (View view)                {//drawer closed after Getactionbar (). Settitle (Mdrawertitle); Invalidateoptionsmenu ();                Creates call to Onprepareoptionsmenu ()} public void ondraweropened (View drawerview) {//Drawer Open                Getactionbar (). Settitle (Mtitle); Invalidateoptionsmenu (); Creates call to Onprepareoptionsmenu ()} @Override the public boolean onoption Sitemselected (MenuItem Item) {if (item! = NULL && item.getitemid () = = Android. R.id.home) {//actionbar on the home icon//end that is gravity.right right-to-left display start that left-to-right pop-up displays if (mDr Awerlayout.isdrawervisible (Gravitycompat.end)) {mdrawerlayout.closedrawer (gravitycompat.end);//Close pumping Drawers} else {mdrawerlayout.opendrawer (gravitycompat.END);//Open Drawer} return true;            } return false;        }        }; Mdrawerlayout.setdrawerlistener (Mdrawertoggle);//Set Drawer listener if (savedinstancestate = = null) {//SelectItem (0        ); }} @Override public boolean Oncreateoptionsmenu (Menu menu) {//Load menu sdk3.0 After menu is included in Actionbar Menuinfla        ter Inflater = Getmenuinflater ();        Inflater.inflate (R.menu.main, menu);    return Super.oncreateoptionsmenu (menu); }/* 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 = Mdrawerla        Yout.isdraweropen (mdrawerlist); Menu.finditem (R.id.action_websearch). setvisible (!draweropen),//search display contrary to drawer return    Super.onprepareoptionsmenu (menu); } @Override public boolean onoptionsitemselected (menUitem item) {//The Action Bar Home/up action should open or close the drawer.        Actionbardrawertoggle would take care of this.        if (mdrawertoggle.onoptionsitemselected (item)) {return true; }//Handle action buttons switch (Item.getitemid ()) {case R.id.action_websearch://creat            E Intent to perform web search for this planet intent intent = new Intent (Intent.action_web_search);            Intent.putextra (Searchmanager.query, Getactionbar (). GetTitle ()); Catch event that there's no activity to handle intent if (Intent.resolveactivity (Getpackagemanager ())! = nul            L) {startactivity (intent);            } else {Toast.maketext (this, r.string.app_not_available, Toast.length_long). Show ();        } return true;        Default:return super.onoptionsitemselected (item); }}/* The Click Listner for the NavigatIon Drawer */Private class Draweritemclicklistener implements Listview.onitemclicklistener {@Override P        ublic void Onitemclick (adapterview<?> parent, view view, int position, long id) {SelectItem (position); }}//content area display planetfragment private void selectitem (int position) {//update the main content by re        Placing fragments Fragment Fragment = new Planetfragment ();        Bundle args = new bundle ();        Args.putint (planetfragment.arg_planet_number, position);        Fragment.setarguments (args);        Fragmentmanager Fragmentmanager = Getfragmentmanager ();        Fragmentmanager.begintransaction (). replace (R.id.content_frame, fragment). commit (); Update selected item and title, then close the drawer//mdrawerlist.setitemchecked (position, true);//Set        Title (Mplanettitles[position]);    Mdrawerlayout.closedrawer (mdrawerlist); } @Override public void Settitle (charsequence title) {MdraWertitle = title;    Getactionbar (). Settitle (Mdrawertitle); }/** * When using the Actionbardrawertoggle, you must call it during * Onpostcreate () and Onconfigurationchang Ed () ... */@Override protected void Onpostcreate (Bundle savedinstancestate) {super.onpostcreate (savedins        Tancestate);        Sync the toggle state after onrestoreinstancestate have occurred.    Mdrawertoggle.syncstate (); } @Override public void onconfigurationchanged (Configuration newconfig) {super.onconfigurationchanged (Newcon        FIG);    Pass any configuration change to the drawer Toggls mdrawertoggle.onconfigurationchanged (newconfig); }/** * Fragment that appears in the "Content_frame", shows a planet */public static class Planetfragment E        Xtends Fragment {public static final String Arg_planet_number = "Planet_number";        Public planetfragment () {//Empty constructor required for fragment subclasses} @Override Public View oncreateview (layoutinflater inflater, ViewGroup container, Bundle sav            Edinstancestate) {View Rootview = inflater.inflate (R.layout.fragment_planet, container, false);            int i = getarguments (). GetInt (Arg_planet_number);            String Planet = Getresources (). Getstringarray (R.array.planets_array) [i];                            Find out the ID of the res-drawable resource int imageId = Getresources (). Getidentifier (Planet.tolowercase (Locale.getdefault ()),            "Drawable", Getactivity (). Getpackagename ());            ((ImageView) Rootview.findviewbyid (R.id.image)). Setimageresource (ImageId);            Getactivity (). Settitle (planet);        return rootview; }    }}



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.