Android AppBarLayout like Whatsapp Tutorial/Example

AppBarLayout is a vertical LinearLayout which implements various material design scrolling gestures.if you are not aware of Material Design refer here.

AppBarLayout children should provide scrolling behaviour by setScrollFlags(int) or in XML by app:layout_scrollFlags=””

Note: AppBarLayout depends heavily on being used as a direct child of Coordinator layout if you used with other ViewGroup its most of the scrolling functionality will not work.

So, Lets start:-

  1. Add following dependencies in build.gradle to work with AppBarLayout
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
  2. Create a layout containing AppBarLayout

activity_main.xml

<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <android.support.design.widget.AppBarLayout
         android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
      >
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:layout_scrollFlags="scroll|enterAlways|snap"
            android:background="#6495ED"
            />
        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#6495ED"
            />
    </android.support.design.widget.AppBarLayout>
    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        />
</android.support.design.widget.CoordinatorLayout>

app:layout_behavior describes the scroll behaviour of view pager it starts scroll below tab layout.

3.Now create a layout for fragment to show items

about.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/recyclerview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

4. Now create a layout  for recyclerview items

listitems.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="8dp"
    android:paddingBottom="8dp"
    android:gravity="center_vertical">
<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    card_view:cardCornerRadius="4dp"
    android:elevation="8dp"
    >
    <TextView
        android:id="@+id/itemname"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:padding="8dp"
        />
    </android.support.v7.widget.CardView>
</LinearLayout>

5.Now create a fragment and adapter for view pager

about.java

package com.coderzpassion.constitution.constitutionofindia;


import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by coderzpassion on 05/04/16.
 */
public class About extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        RecyclerView recyclerView=(RecyclerView) inflater.inflate(R.layout.about,container,false);
        setUpRecyclerView(recyclerView);
        return  recyclerView;
    }

    private void setUpRecyclerView(RecyclerView rv)
    {
        rv.setLayoutManager(new LinearLayoutManager(rv.getContext()));
        rv.setAdapter(new AboutUsAdapter(rv.getContext(), getListForItems()));
    }
    public ArrayList<String> getListForItems()
    {
        ArrayList<String> list =new ArrayList<>();
        list.add("First Item");
        list.add("Second Item");
        list.add("Third Item");
        list.add("Fourth Item");
        list.add("Fifth Item");
        list.add("Six Item");
        list.add("Seven Item");
        list.add("8 Item");
        list.add("9 Item");
        list.add("10 Item");
        list.add("11 Item");
        list.add("12 Item");
        list.add("13 Item");
        list.add("14 Item");
        list.add("15 Item");
        list.add("16 Item");
        list.add("17 Item");
        list.add("18 Item");
        list.add("19 Item");
        list.add("20 Item");
        list.add("21 Item");

        return list;
    }

    public  static class AboutUsAdapter extends RecyclerView.Adapter<AboutUsAdapter.ViewHolder>
    {
        ArrayList<String> aboutlist=new ArrayList<>();
        Context aboutuscontext;

             public static class ViewHolder extends RecyclerView.ViewHolder
             {
                 public final TextView items;
                public ViewHolder(View view)
                {
                    super(view);
                    items=(TextView)view.findViewById(R.id.itemname);
                }
             }

        public AboutUsAdapter(Context context,ArrayList<String> list)
        {
            aboutuscontext=context;
            aboutlist=list;

        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
           View view=LayoutInflater.from(parent.getContext()).inflate(R.layout.listitems, parent, false);
            return  new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
                 holder.items.setText(aboutlist.get(position));
        }

        @Override
        public int getItemCount() {
            return aboutlist.size();
        }
    }
}

6.Now create a MainActivity and code for AppBarLayout

MainActivity.java

package com.coderzpassion.constitution.constitutionofindia;

import android.database.DataSetObserver;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar=(Toolbar)findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        final ActionBar actionBar=getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(false);
        ViewPager viewPager=(ViewPager)findViewById(R.id.viewpager);
        if(viewPager!=null)
        {
            setUpViewPager(viewPager);
        }
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }
       private void setUpViewPager(ViewPager viewPager)
        {
            Adapter adapter=new Adapter(getSupportFragmentManager());
            adapter.addFragment(new About(),"Article 1");
            adapter.addFragment(new About(),"Article 2");
            adapter.addFragment(new About(),"Article 3");

            viewPager.setAdapter(adapter);
           }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
    static class Adapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragments = new ArrayList<>();
        private final List<String> mFragmentTitles = new ArrayList<>();

        public Adapter(FragmentManager fm) {
            super(fm);
        }

        public void addFragment(Fragment fragment, String title) {
            mFragments.add(fragment);
            mFragmentTitles.add(title);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitles.get(position);
        }
    }
}

Output

appbarlayoutlikewhatsapp    workingwithappbarlayout    makingtoolbarlikewhatsapp

 

 

Show Sliding Menu Using Navigation View Android Tutorial

Navigation View was introduced with Material Design Support Library. Navigation is very easy to implement , so it is easy to customize it and looks great and is very smooth.

If you are unaware of Material Design visit here.It is necessary you should have knowledge of Material Design.

So, Lets start:- Navigation View has two Main Components i.e Header View and  Menu.

Header View 

This is the top part of Navigation View usually containing Profile Picture and username like in apps like Gmail,Facebook etc.

Menu

The menu is the part below Header View and consists the menu which is defined under res->menu folder. So, Together menu and header view act as a Navigation view containing all  the options for a user.

Requirements:-

1.Open  Android Studio -> New Project->Android Application Project-> Name of Application-> Follow all instructions and complete by clicking on Finish.

2.Make sure your current theme does not have ActionBar by default like mine is Theme.AppCompat.Light.NoActionBar under res->values->styles.xml

3.Now add a dependency in build.gradle to work with material design

compile 'com.android.support:design:23.1.1'

4.Now create header.xml and menu.xml for Navigation View

header.xml under res->layout->header.xml

here i am using imageview and textview to show image and email althought you can change according to your requirements like circleimageview and textview

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#7ac5cd">

    <ImageView
        android:id="@+id/profileimage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/logo"
        android:padding="20dp"
        android:layout_gravity="center"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="coderzpassion@gmail.com"
        android:padding="20dp"/>
</LinearLayout>

menu_main.xml under res->menu->menu_main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity">
    <group android:checkableBehavior="single">
    <item
        android:id="@+id/home"
        android:title="Home"
        android:checked="false"/>
        <item
            android:id="@+id/inbox"
            android:title="Inbox"
            android:checked="false"/>
        <item
            android:id="@+id/outbox"
            android:title="Outbox"
            android:checked="false"/>
        <item
            android:id="@+id/sent"
            android:title="Sent"
            android:checked="false"/>
        <item
            android:id="@+id/aboutus"
            android:title="About Us"
            android:checked="false"/>
    </group>
</menu>

 Note: here i am using checkableBehavior=”single” to select single menu item you can also use none or all.

5.Now create a layout for activity containing Navigation View.In this i am using DrawerLayout attribute fitsSystemWindows=”true” so that Navigation should come above toolbar also. in this layout i am using Framelayout to contain all fragments and Using Navigation View attribute app:headerLayout=”@layout/header” to set header to Navigation View and app:menu=”menu/menu_main” to set menu items and use layout_gravity=”start” to start Navigation View from left or start.

activity_main.xml

<android.support.v4.widget.DrawerLayout
    android:id="@+id/drawer"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    fitsSystemWindows="true"
    >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            ></android.support.v7.widget.Toolbar>
        <FrameLayout
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </FrameLayout>
    </LinearLayout>
<android.support.design.widget.NavigationView
    android:id="@+id/navigationview"
    android:layout_height="match_parent"
    android:layout_width="wrap_content"
    android:layout_gravity="start"
    app:headerLayout="@layout/header"
    app:menu="@menu/menu_main"
    ></android.support.design.widget.NavigationView>

</android.support.v4.widget.DrawerLayout>

6. Now Define some Strings to use in our Application under res->values->strings.xml

strings.xml

<resources>
    <string name="app_name">Navigation Sample</string>
    <string name="draweropened">Drawer Opened</string>
    <string name="drawerclosed">Drawer Closed</string>
 
</resources>

7.Now create a layout for fragment which will be shown when you click on MenuItem or you can on options showed on Navigation View.

navigationfragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"/>

</LinearLayout>

8.Now create a Fragment for above layout

NavigationFragment

package com.coderzpassion.navigationviewsample;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.TextView;


/**
 * Created by apple on 20/02/16.
 */
public class NavigationFragment extends Fragment {

    String titleforfragment="";

    public NavigationFragment()
    {

    }
public static NavigationFragment newInstance(String title)
{
    NavigationFragment ap=new NavigationFragment();
    Bundle b=new Bundle();
    b.putString("title",title);
    ap.setArguments(b);
    return  ap;
}

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        titleforfragment=getArguments().getString("title");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.navigationfragment, container, false);
        TextView title=(TextView)rootView.findViewById(R.id.title);
        title.setText(titleforfragment);

        return rootView;
    }
}

9. Now Code for Navigation View in MainActivity.java

MainActivity.java

package com.coderzpassion.navigationviewsample;

import android.graphics.Color;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    //defining widgets
    private Toolbar toolbar;
    private NavigationView navigationView;
    private DrawerLayout drawerLayout;
    NavigationFragment fragment=null;
    android.support.v4.app.FragmentTransaction fragmentTransaction=null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //initialising the widgets
        toolbar=(Toolbar)findViewById(R.id.toolbar);

        navigationView=(NavigationView)findViewById(R.id.navigationview);
        drawerLayout=(DrawerLayout)findViewById(R.id.drawer);

        //setting the toolbar as actionbar
        setSupportActionBar(toolbar);

        //setting background color of toolbar
        toolbar.setBackgroundColor(Color.parseColor("#0081c9"));

        //handling click of Navigation View items
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {
                if(menuItem.isChecked())
                    menuItem.setChecked(false);
                else
                menuItem.setChecked(true);
                drawerLayout.closeDrawers();

                return displayFragment(menuItem.getItemId());
            }
        });

        //creating ActionBarDrawerToggle
        ActionBarDrawerToggle actionBarDrawerToggle=new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.draweropened,R.string.drawerclosed)
        {
            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
            }
        };
        //binding ActionBarDrawerToggle to DrawerLayout
        drawerLayout.setDrawerListener(actionBarDrawerToggle);

        //calling sync state is compulsory to avoid unusual behaviour as home button wont show up
        actionBarDrawerToggle.syncState();

        //showing Fragment for FirstTime
        if(savedInstanceState==null)
        {
            displayFragment(R.id.inbox);
        }

    }

    public boolean displayFragment(int id)
    {
        switch (id)
        {
            case R.id.home:
                Toast.makeText(getApplicationContext(), "Home Selected", Toast.LENGTH_SHORT).show();
                fragment=NavigationFragment.newInstance("Home");
                fragmentTransaction = getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.container,fragment);
                fragmentTransaction.commit();
                return true;
            case R.id.inbox:
                Toast.makeText(getApplicationContext(), "Inbox Selected", Toast.LENGTH_SHORT).show();
                fragment=NavigationFragment.newInstance("Inbox");
                fragmentTransaction = getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.container,fragment);
                fragmentTransaction.commit();
                return true;
            case R.id.outbox:
                Toast.makeText(getApplicationContext(), "Outbox Selected", Toast.LENGTH_SHORT).show();
                fragment=NavigationFragment.newInstance("Outbox");
                fragmentTransaction = getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.container,fragment);
                fragmentTransaction.commit();
                return true;
            case R.id.sent:
                Toast.makeText(getApplicationContext(), "Sent Selected", Toast.LENGTH_SHORT).show();
                fragment=NavigationFragment.newInstance("Sent");
                fragmentTransaction = getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.container,fragment);
                fragmentTransaction.commit();
                return true;
        }
        return false;
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
     //   getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        return super.onOptionsItemSelected(item);
    }
}

Output

slidingmenuusingnavigationview  androidhowtoshowslidingmenuusingnavigationview

 

 

Showing Sliding Menu Using Navigation Drawer Android Tutorial

Nowadays, Lot of application’s use sliding menu to show the major functionality of their application.Applications like facebook, youtube, Gmail use sliding to navigate between major options. Now this sliding menu in android is done with the use of Navigation Drawer.

So, Let’s and add sliding menu to the application:-

Will need the following to implement Sliding Menu

1.I will have MainActivity containg drawerlayout in xml.

2.I will have one Listview for Sliding Menu items.

3. Adapter class to be bind to listview i will be using simple layout for adapter containg textview however you can customize according to your needs like adding image also.

So, Let’s Start by creating the project:-

1.Open Eclipse or Android Studio -> New Project->Android Application Project-> Name of Application-> Follow all instructions and complete by clicking on Finish.

2.Open strings.xml under res->values->strings.xml or create one if you not find and define items for sliding  menu

strings.xml

<!-- Navigation Drawer Menu Items -->
    <string-array name="nav_drawer_items">
        <item >Home</item>
        <item >Colleges and Universities</item>
        <item >Sports and Culture</item>
        <item >Tourism</item>
        <item >Explore Districts</item>
        <item >Explore DistrictMap</item>
        <item >Disclaimer</item>
    </string-array>

3.Create a layout for your Activity containing Navigation Drawer

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

    <!-- Framelayout to display Fragments -->
    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <!-- Listview to display Navigation Drawer items -->
    <ListView
        android:id="@+id/list_slidermenu"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:background="#33CCCC"
       />
</android.support.v4.widget.DrawerLayout>

4.Now Create a layout for your Adapter which will be set to ListView inside Navigation Drawer

drawer_list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/title"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:textSize="20dp"
        android:padding="5dp"
        />

</LinearLayout>

5. Now Define your Adapter class

NavDrawerListAdapter.java

package com.coderzpassion.punjab.explorepunjab;

import android.app.Activity;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

/**
 * Created by apple on 20/02/16.
 */public class NavDrawerListAdapter extends BaseAdapter {

    private Context context;
    private String [] navDrawerItems;

    public NavDrawerListAdapter(Context context, String [] navDrawerItems){
        this.context = context;
        this.navDrawerItems = navDrawerItems;
    }

    @Override
    public int getCount() {
        return navDrawerItems.length;
    }

    @Override
    public Object getItem(int position) {
        return navDrawerItems[position];
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            LayoutInflater mInflater = (LayoutInflater)
                    context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            convertView = mInflater.inflate(R.layout.drawer_list_item, null);
        }


        TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
      
        txtTitle.setTypeface(Typeface.createFromAsset(context.getAssets(), "Personal_Use.ttf"));
        txtTitle.setText(navDrawerItems[position]);

        return convertView;
    }

}

setting the background of action bar

final android.support.v7.app.ActionBar ab=getSupportActionBar();
        // setting the background color
        ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#33CCCC")));

setting custom view for Action Bar

//setting custom view for Action Bar
       getSupportActionBar().setCustomView(R.layout.action_bar_layout);

handling the click of Sliding menu Items

mDrawerList.setOnItemClickListener(new SlidingMenuClickListener());

private class SlidingMenuClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            // display view for selected nav drawer item
            displayView(position);
        }
    }

    /**
     * Diplaying fragment view for selected nav drawer list item
     * */
    private void displayView(int position) {
        // update the main content by replacing fragments
        Fragment fragment = null;
        switch (position) {
            case 0:
                fragment = AboutPunjab.newInstance("Punjab.html");

                break;
            case 1:
                fragment = AboutPunjab.newInstance("universities.html");
                break;
            case 2:
                fragment = AboutPunjab.newInstance("sportsandculture.html");
                break;
            case 3:
                fragment = AboutPunjab.newInstance("tourism.html");
                break;
            case 4:
                fragment = ExploreDistricts.newInstance("Punjab.html");
                break;
            case 5:
                fragment = ExploreMaps.newInstance("Punjab.html");
                break;
            case 6:
                fragment = AboutPunjab.newInstance("disclaimer.html");
                break;

            default:
                break;
        }

6. Now Create MainActivity.java and code for NavigationDrawer 

MainActivity.java

package com.coderzpassion.punjab.explorepunjab;

import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {

    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    // nav drawer title
    private CharSequence mDrawerTitle;

    // used to store app title
    private CharSequence mTitle;

    // slide menu items
    private String[] navMenuTitles;
    private TypedArray navMenuIcons;

   // private ArrayList<NavDrawerItem> navDrawerItems;
    private NavDrawerListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
        mTitle = mDrawerTitle = getTitle();
        navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
        mDrawerList.setOnItemClickListener(new SlidingMenuClickListener());

        // setting the nav drawer list adapter
        adapter = new NavDrawerListAdapter(getApplicationContext(),navMenuTitles);
        mDrawerList.setAdapter(adapter);
        // getting actionbar
        final android.support.v7.app.ActionBar ab=getSupportActionBar();
        // setting the background color
        ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#33CCCC")));
       

        // enabling action bar app icon and behaving it as toggle button
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayShowCustomEnabled(true);
        //setting custom view for Action Bar
        getSupportActionBar().setCustomView(R.layout.action_bar_layout);


        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.drawable.menu,
                 //nav menu toggle icon
                R.string.app_name, // nav drawer open - description for accessibility
                R.string.app_name // nav drawer close - description for accessibility
        ){
            public void onDrawerClosed(View view) {
                getSupportActionBar().setTitle(mTitle);
                // calling onPrepareOptionsMenu() to show action bar icons
                invalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                getSupportActionBar().setTitle(mDrawerTitle);
                // calling onPrepareOptionsMenu() to hide action bar icons
                invalidateOptionsMenu();
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            // on first time display view for first nav item
            displayView(0);
        }


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        //getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement


        return super.onOptionsItemSelected(item);
    }

    private class SlidingMenuClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            // display view for selected nav drawer item
            displayView(position);
        }
    }

    /**
     * Diplaying fragment view for selected nav drawer list item
     * */
    private void displayView(int position) {
        // update the main content by replacing fragments
        Fragment fragment = null;
        switch (position) {
            case 0:
                fragment = AboutPunjab.newInstance("Punjab.html");

                break;
            case 1:
                fragment = AboutPunjab.newInstance("universities.html");
                break;
            case 2:
                fragment = AboutPunjab.newInstance("sportsandculture.html");
                break;
            case 3:
                fragment = AboutPunjab.newInstance("tourism.html");
                break;
            case 4:
                fragment = ExploreDistricts.newInstance("Punjab.html");
                break;
            case 5:
                fragment = ExploreMaps.newInstance("Punjab.html");
                break;
            case 6:
                fragment = AboutPunjab.newInstance("disclaimer.html");
                break;

            default:
                break;
        }

        if (fragment != null) {
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.frame_container, fragment).commit();

            // update selected item and title, then close the drawer
            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
            //setting the title according to navMenuitem
            mTitle=navMenuTitles[position];
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            // error in creating fragment
            Log.e("MainActivity", "Error in creating fragment");
        }
    }
    @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 toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }
}

7.Creating Fragment to show when Clicking on Sliding Menu Item’s

AboutPunjab.java

package com.coderzpassion.punjab.explorepunjab;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;

/**
 * Created by apple on 20/02/16.
 */
public class AboutPunjab extends Fragment {

    String title="";

    public AboutPunjab()
    {

    }
public static AboutPunjab newInstance(String title)
{
    AboutPunjab ap=new AboutPunjab();
    Bundle b=new Bundle();
    b.putString("title",title);
    ap.setArguments(b);
    return  ap;
}

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
      title=getArguments().getString("title");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.allfragments, container, false);
        WebView webView =(WebView)rootView.findViewById(R.id.mainwebview);
        webView.loadUrl("file:///android_asset/"+title);
     
    
        return rootView;
    }
}

8. layout for Fragment

allfragments.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
<WebView
    android:id="@+id/mainwebview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_above="@+id/adView"></WebView>
   
</RelativeLayout>

Output

slidingmenu

How to show/display Alert Dialog/Dialog in Android.

In this post, I will show you how to show alertDialog in Android. AlertDialog is used largely to show alerts or confirmation messages to the user. Alert Dialog is very easy to create.

So, Let’s Start:-

Simple AlertDialog with “OK” Button

//create alertDialogBuilder
     AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);

     // set title
     alertDialogBuilder.setTitle("CoderzPassion");

     // set dialog message
     alertDialogBuilder
             .setMessage("Welcome To CoderzPassion!Keep Visting for Android Tutorials")
             .setCancelable(false)
             .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface dialog, int id) {
                     // if this button is clicked, do something here i am displaying Toast Message

                     Toast.makeText(MainActivity.this, "You clicked On Ok Button ", Toast.LENGTH_SHORT).show();
                 }
             });

     // create alert dialog
     AlertDialog alertDialog = alertDialogBuilder.create();

     // show it
     alertDialog.show();

AlertDialog with “Two” Buttons

//create alertDialogBuilder
       AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);

       // set title
       alertDialogBuilder.setTitle("Your Title");

       // set dialog message
       alertDialogBuilder
               .setMessage("Click yes to exit!")
               .setCancelable(false)
               .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       // if this button is clicked,  do something here i am displaying Toast Message
                       Toast.makeText(MainActivity.this, "You clicked On Yes ", Toast.LENGTH_SHORT).show();
                   }
               })
               .setNegativeButton("No", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       // if this button is clicked, just close
                       // the dialog box and do nothing
                       dialog.cancel();
                   }
               });

       // create alert dialog
       AlertDialog alertDialog = alertDialogBuilder.create();

       // show it
       alertDialog.show();

AlertDialog with Three Button (One Neutral Button)

//create alertDialogBuilder
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);

        // set title
        alertDialogBuilder.setTitle("Your Title");

        // set dialog message
        alertDialogBuilder
                .setMessage("Click yes to exit!")
                .setCancelable(false)
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // if this button is clicked,  do something here i am displaying Toast Message
                        Toast.makeText(MainActivity.this, "You clicked On Yes ", Toast.LENGTH_SHORT).show();
                    }
                })
                .setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //cancel the dialog box
                        dialog.cancel();
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // if this button is clicked,  do something here i am displaying Toast Message
                        Toast.makeText(MainActivity.this, "You clicked On No ", Toast.LENGTH_SHORT).show();

                    }
                });

        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();

        // show it
        alertDialog.show();

 Creating Custom Dialog

layout for CustomDialog

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#D3D7DB"
    android:orientation="vertical" >
    
    
    <TextView android:id="@+id/dialogtitle"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textColor="@android:color/black"
        android:text="Please enter the email address you used for the account"
        />

    <EditText
        android:id="@+id/emailedittext"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:ems="10"
        android:padding="5dp"
        android:cursorVisible="true"
        android:singleLine="true"
        android:background="@android:color/white"
        android:textColor="@android:color/black"
        android:hint="Enter Mail id"
        android:textSize="20dp" >

        <requestFocus />
    </EditText>
    
    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:weightSum="2"
        android:orientation="horizontal">
        
         <Button 
            android:id="@+id/cancelbtn"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="CANCEL"/>
         
          <Button 
            android:id="@+id/okbtn"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="Ok"/>
    </LinearLayout>

</LinearLayout>

Creating Dialog using the above layout

final Dialog dialog = new Dialog(MainActivity.this);
      // Include dialog.xml file
      dialog.setContentView(R.layout.forgotpassword);
      // Set dialog title
      dialog.setTitle("ALERT!!");

      // set values for custom dialog components - text, image and button
      Button okbtn = (Button) dialog.findViewById(R.id.okbtn);
      Button cancelbtn = (Button) dialog.findViewById(R.id.cancelbtn);
      final EditText emailedittext = (EditText) dialog.findViewById(R.id.emailedittext);

      dialog.show();
      dialog.getWindow().setSoftInputMode(
              WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

      // if decline button is clicked, close the custom dialog
      cancelbtn.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              // Close dialog
              dialog.dismiss();
          }
      });
      okbtn.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              String email=emailedittext.getText().toString();
              //do something more here
          }
      });

Final Code Now

MainActivity.java containing button showing alertdialog on clicking the button

//layout for MainActivity

activity_main.xml

<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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">


    <Button
        android:id="@+id/simpledialog"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Show Simple AlertDialog"/>
    <Button
        android:id="@+id/twobuttondialog"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Show Two Button AlertDialog"
        android:layout_below="@+id/simpledialog"/>
    <Button
        android:id="@+id/threebuttondialog"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Show Neutral Button AlertDialog"
        android:layout_below="@+id/twobuttondialog"/>
    <Button
        android:id="@+id/customdialog"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Show Custom AlertDialog"
        android:layout_below="@+id/threebuttondialog"/>

</RelativeLayout>

//layout for custom Dialog

forgotpassword.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#D3D7DB"
  
    android:orientation="vertical" >
    
    
    <TextView android:id="@+id/dialogtitle"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textColor="@android:color/black"
        android:text="Please enter the email address you used for the account"
        />

    <EditText
        android:id="@+id/emailedittext"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:ems="10"
        android:padding="5dp"
        android:cursorVisible="true"
        android:singleLine="true"
        android:background="@android:color/white"
        android:textColor="@android:color/black"
        android:hint="Enter Mail id"
        android:textSize="20dp" >

        <requestFocus />
    </EditText>
    
    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:weightSum="2"
        android:orientation="horizontal">
         
        <Button 
            android:id="@+id/cancelbtn"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="CANCEL"/>
         
          <Button 
            android:id="@+id/okbtn"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="Submit"/>
    </LinearLayout>

</LinearLayout>

MainActivity.java

package com.coderzpassion.alertsample;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    Button simpledialog,twobuttondialog,threebuttondialog,customdialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        simpledialog=(Button)findViewById(R.id.simpledialog);
        //handling the click of simpledialog button
        simpledialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               showSimpleDialog();
            }
        });
        twobuttondialog=(Button)findViewById(R.id.twobuttondialog);
        twobuttondialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               showtwoButtonDialog();
            }
        });
        threebuttondialog=(Button)findViewById(R.id.threebuttondialog);
        //handling the click of threebuttondialog button
        threebuttondialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               showthreeButtonDialog();
            }
        });
        customdialog=(Button)findViewById(R.id.customdialog);
        //handling the click of customdialog button
        customdialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              showCustomDialog();
            }
        });
    }

    public void showSimpleDialog()
    {
        //create alertDialogBuilder
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);

        // set title
        alertDialogBuilder.setTitle("CoderzPassion");

        // set dialog message
        alertDialogBuilder
                .setMessage("Welcome To CoderzPassion!Keep Visting for Android Tutorials")
                .setCancelable(false)
                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // if this button is clicked, do something here i am displaying Toast Message

                        Toast.makeText(MainActivity.this, "You clicked On Ok Button ", Toast.LENGTH_SHORT).show();
                    }
                });


        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();

        // show it
        alertDialog.show();
    }
    public void showtwoButtonDialog()
    {
        //create alertDialogBuilder
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);

        // set title
        alertDialogBuilder.setTitle("Your Title");

        // set dialog message
        alertDialogBuilder
                .setMessage("Click yes to exit!")
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // if this button is clicked,  do something here i am displaying Toast Message
                        Toast.makeText(MainActivity.this, "You clicked On Yes ", Toast.LENGTH_SHORT).show();
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // if this button is clicked, just close
                        // the dialog box and do nothing
                        dialog.cancel();
                    }
                });

        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();

        // show it
        alertDialog.show();
    }
    public void showthreeButtonDialog()
    {
        //create alertDialogBuilder
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);

        // set title
        alertDialogBuilder.setTitle("Your Title");

        // set dialog message
        alertDialogBuilder
                .setMessage("Click yes to exit!")
                .setCancelable(false)
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // if this button is clicked,  do something here i am displaying Toast Message
                        Toast.makeText(MainActivity.this, "You clicked On Yes ", Toast.LENGTH_SHORT).show();
                    }
                })
                .setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //cancel the dialog box
                        dialog.cancel();
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // if this button is clicked,  do something here i am displaying Toast Message
                        Toast.makeText(MainActivity.this, "You clicked On No ", Toast.LENGTH_SHORT).show();

                    }
                });

        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();

        // show it
        alertDialog.show();
    }
    public void showCustomDialog()
    {
        final Dialog dialog = new Dialog(MainActivity.this);
        // Include dialog.xml file
        dialog.setContentView(R.layout.forgotpassword);
        // Set dialog title
        dialog.setTitle("ALERT!!");

        // set values for custom dialog components - text, image and button
        Button okbtn = (Button) dialog.findViewById(R.id.okbtn);
        Button cancelbtn = (Button) dialog.findViewById(R.id.cancelbtn);
        final EditText emailedittext = (EditText) dialog.findViewById(R.id.emailedittext);

        dialog.show();
        dialog.getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

        // if decline button is clicked, close the custom dialog
        cancelbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Close dialog
                dialog.dismiss();
            }
        });
        okbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String email=emailedittext.getText().toString();
                //do something more here
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Output

androidhowtoshowcustomdialogbox        androidworkingwithalertdialog           howtoalertdialoginandroid howtoshowalertdialoginandroid        howtoshowdialogbox