Home android Side menu in Android

Side menu in Android

Author

Date

Category

began to learn Android development recently. I wrote a small application on Android and you need to make the side menu . I tried to make with a template from Android Studio, Navigation Drawer Activity , but since I appeal to you, it is clear that I didn’t work out. I went a lot googled my question, but I have nothing to find a suitable tutorial (the only exception is probably This gorgeous article with Habra , but here’s the infection, it is written here on Kotlin, and I need to java), please tell us Step by , How to create a side menu in Android Studio?


Answer 1, Authority 100%

Here is the instruction how to add a layout to the application. We will consider the situation when you create a new application, given the information provided in the question. When creating a new project, you can choose Drawer Activity how you have already tried and then the studio will do everything for you. All the necessary classes will be created for support, markup (which can be custom at your discretion), resources for the menu and the like. To figure out what for which in this version is completely simple. There is a second option – create an application based on empty activity (Empty Activity) and then do everything manually. First you need to create a project and go to the Activity_main.xml markup file and add the appropriate code:

& lt; 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" & gt;
   & lt;! - The Main Content View - & gt;
   & LT; FrameLayout
       Android: id = "@ + ID / CONTENT_FRAME"
       Android: layout_width = "Match_Parent"
       Android: layout_height = "match_parent" / & gt;
   & lt;! - The Navigation Drawer - & GT;
    & lt; 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" / & gt;
& lt; /android.support.v4.widget.drawerlayout>

Next you need to add menu items that will be displayed, for this, go to the string resource file and add an array with your data:

& lt; string-array name = "screen_array" & gt;
    & lt; Item & gt; Screen 1 & lt; / Item & gt;
    & lt; Item & gt; Screen 2 & lt; / Item & gt;
    & lt; Item & gt; Screen 3 & lt; / Item & gt;
  & lt; / String-Array & GT;

The next step will be the creation of the menu item markup, so we create the file drawer_list_item.xml :

& lt; textview xmlns: android = "http://schemas.android.com/apk/res/android"
  Android: id = "@ Android: ID / TEXT1"
  Android: layout_width = "Match_Parent"
  Android: layout_height = "wrap_content"
  Android: Background = "@ Drawable / Activated_BackGround"
  Android: Gravity = "Center_Vertical"
  Android: minHeight = "? attr / listpreferreditemheightsmall"
  Android: Paddingleft = "16DP"
  Android: paddingright = "16dp"
  Android: TextAppearance = "? Android: attr / textappeaancemedium"
  Android: TextColor = "# FFF" / & gt;

After creating the markup of the menu item, you need to think about how the presses and mark the selected menu item will be displayed, so we create Drawable file in the file>activated_background.xml folder:

& lt; selector xmlns: android = "http://schemas.android.com/apk/res/android" & gt;
  & lt; Item Android: Drawable = "@ Color / Blue" Android: state_activated = "true" / & gt;
  & lt; Item Android: Drawable = "@ Color / Blue" Android: state_selected = "True" / & gt;
  & lt; Item Android: Drawable = "@ Color / Blue" Android: state_pressed = "True" / & gt; 
& lt; Item Android: Drawable = "@ Color / Blue" Android: state_checked = "True" / & gt;
  & lt; Item Android: Drawable = "@ Android: Color / Transparent" / & gt;
& lt; / selector & gt;

and in color resources add the desired color:

& lt; item name = "blue" type = "color" & gt; # FF33B5E5 & lt; / Item & gt;

After the design is completed, you need to think about the logic of the behavior of our menu, here is the activity:

Public Class MainActivity Extends ActionBaractivity {
  Private String [] mscreentitles;
  Private DrawerLayout MDrawerLayout;
  Private ListView MDrawerList;
  PRIVATE ACTIONBARDRAWERTOGGLE MDRAWERTOGGLE;
  Private Charsequence MDRewertitle;
  Private Charsequence Mtitle;
  @Override
  PROTECTED VOID OnCreate (Bundle SavedInstanceState) {
    Super.ONCREATE (SavedInstanceState);
    setContentView (R.Layout.Activity_Main);
    Mtitle = MDRewertitle = Gettitle ();
    mscreentitles = getResources (). getStringArray (R.Array.screen_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 & lt; string & gt; (this,
        R.layout.drawer_list_item, mscreentitles));
    // Set The List's Click Listener
    mdrawerlist.setonitemclicklistener (new diaperitemclicklistener ());
    getSupportactionBar (). SETDISPLAYHOMEASPENABED (TRUE);
    getSupportactionBar (). SethomeButTonEnabled (True);
    MDRewertoggle = New ActionBardRawertoggle (
        This, / * Host Activity * /
        MDrawReerLayout, / * Drawerlayout Object * /
        R.Drawable.ic_drawer, / * Nav Drawer icon to replace 'up' caret * /
        R.string.drawer_open, / * "Open Draw" Description * /
        R.String.Drawer_Close / * "Close Drawer" Description * /
        ) {
      / ** Called WHEN A Drawer Has Settled in a Completely Closed State. * /
      Public Void OnDRaverClosed (View View) {
        getSupportactionBar (). Settitle (Mtitle);
        supportInvalidateOptionsMenu (); // Creates Call to OnprepareOptionSMenu ()
      }
      / ** Called WHEN A Drawer Has Settled in a Completely Open State. * /
      Public Void Ondraweropened (View DrawerView) {
        getSupportactionBar (). Settitle (MDRewertitle);
        supportInvalidateOptionsMenu (); // Creates Call to OnprepareOptionSMenu ()
      }
    };
    // Set The Drawer Toggle AS The Drawerlistener
    MDrawerLayout.SetDrawRlistener (MDRewertoggle);
    // Initialize The First Fragment When The Application First Loads.
    If (SavedInstanceState == NULL) {
      SelectItem (0);
    }
  }
  @Override
  Public Boolean OnCreateOptionsMenu (Menu Menu) {
    // Inflate The Menu;
    Menuinflater 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 = MDrawerLayout.ISDRAWEROPEN (MDrawerList);
    menu.finditem (R.ID.Action_Search) .setvisible (! Draweropen);
    Return Super.ONPREPAREOPTIONSMENU (MENU);
  }
  @Override
  Public Boolean OnoPtionSetemSelected (MenuItem Item) {
    // Pass The Event to ActionBardraWeRToggle, if it returns
    // True, Then It Has Handled The App Icon Touch Event
    if (mdrawertoggle.onoptionsiMselected (Item)) {
      RETURN TRUE;
    }
     // Handle Action Buttons
    Switch (Item.GetiteMid ()) {
    Case R.ID.Action_Search:
      // Show toast About Click.
      Toast.maketext (this, r.string.action_search, toast.length_short) .show ();
      RETURN TRUE;
    Default:
      RETURN SUPER.ONOPTIONSIEMSELECTED (Item);
    }
  } 
/ * The click listener for ListView in the navigation drawer * /
  private class DrawerItemClickListener implements ListView.OnItemClickListener {
    @Override
    public void onItemClick (AdapterView & lt;? & gt; parent, View view, int position, long id) {
      selectItem (position);
    }
  }
  / ** Swaps fragments in the main content view * /
  private void selectItem (int position) {
    // Update the main content by replacing fragments
    Fragment fragment = null;
    switch (position) {
    case 0:
      fragment = new ScreenOne ();
      break;
    case 1:
      fragment = new ScreenTwo ();
      break;
    case 2:
      fragment = new ScreenThree ();
      break;
    default:
      break;
    }
    // Insert the fragment by replacing any existing fragment
    if (fragment! = null) {
      FragmentManager fragmentManager = getSupportFragmentManager ();
      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 (mScreenTitles [position]);
      mDrawerLayout.closeDrawer (mDrawerList);
    } else {
      // Error
      Log.e (this.getClass (). GetName (), "Error. Fragment is not created");
    }
  }
  @Override
  public void setTitle (CharSequence title) {
    mTitle = title;
    getSupportActionBar (). setTitle (mTitle);
  }
  / **
   * When using the ActionBarDrawerToggle, you must call it during
   * onPostCreate () and onConfigurationChanged () ...
   * /
  @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);
    // Pass any configuration change to the drawer toggles
    mDrawerToggle.onConfigurationChanged (newConfig);
  }
}

well, for correct operation, you need to create the required number of fragments that will show the user some data:

public class ScreenOne extends Fragment {
  public ScreenOne () {
  }
  @Override
  public View onCreateView (LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View rootView = inflater.inflate (R.layout.screen_first, container,
        false);
    return rootView;
  }
}

for each fragment, you can make your own markup. Here is the tutorial .


Answer 2, authority 11%

You will not have a step-by-step solution here. Read community guidelines , it doesn’t like this approach. Here they help to solve a specific problem, and do not write manuals to order.

but since I am asking you, it is clear that nothing worked for me

If it didn’t work out, it means you did something wrong. All studio templates work out of the box, tested by more than one generation of programmers. If it does not work for you, create a new question, where indicate what exactly is wrong: what error it gives at startup, for example. But such questions will be rather quickly minus and deleted.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions