Android ActionBar - DropDown Navigation - Then NavigationListener


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.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post