Android ActionBar - DropDown Navigation - Then NavigationListener

September 2, 2017 Oclemy Android ActionBar, Android Menu 1 minute, 10 seconds

Android ActionBar Dropdown Navigation List

This is an android actionbar dropdown menu example.Display a simple dropdown menu and handle its itemClicks.

Section 1 : MainActivity

    package com.tutorials.dropdownnav;

    import android.app.ActionBar;
    import android.app.ActionBar.OnNavigationListener;
    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.ArrayAdapter;
    import android.widget.Toast;

    public class MainActivity extends Activity {

      //DROPDOWN MENU ITEMS
      String[] actions={"Add","Save","Update","Delete","Copy"};
      ArrayAdapter<String> adapter;

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

            //ADAPTER INITIALIZATION
            adapter=new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, actions);

            //GET ACTIONBAR
            ActionBar ab=getActionBar();

            ab.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

            //GET ACTIONBAR LISTENER
            ActionBar.OnNavigationListener listener=new OnNavigationListener() {

          @Override
          public boolean onNavigationItemSelected(int pos, long id) {
            // WE SHOW SIMPLE TOAST WHEN A DROPDOWN ITEM IS SELECTED
            Toast.makeText(getApplicationContext(), actions[pos], Toast.LENGTH_SHORT).show();
            return false;
          }
        };
        //SET ADAPTER AND LISTENER TO ACTION BAR
        ab.setListNavigationCallbacks(adapter, listener);

        }

    }

Layout

  • This is our layout. We include nothing of note.

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context=".MainActivity" >
    
    </RelativeLayout>

Good day.

Comments