Menus in Android

Menus is a most important part of android application.menu are use for handle common features of activity.
In this tutorial we will learn about how to create menu in application with simple ways.

Type of Menu:-there are two type of menu in android 

1. Option menu
2. Context menu

1) Options menu

Now we will learn to create option menu with simple step.

1.Now first Create a folder named menu inside your project res directory.Now let us add a new xml file named menu_item.xml file 
2.add item in menu_item.xml.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
<!-- this is first for Search item-->
<item
        android:id="@+id/action_search1"
        android:title="Profile"
        android:orderInCategory="100"
        android:icon="@android:drawable/ic_menu_search"
        app:showAsAction="ifRoom" />
    <!-- this is use for Search item-->
    <item
        android:id="@+id/action_search"
        android:icon="@android:drawable/ic_menu_search"
        app:showAsAction="always"
        app:actionViewClass="android.support.v7.widget.SearchView"
        android:title="Search"/>
   <!-- this is use for setting option-->
    <item
        android:id="@+id/action_settings"
        android:title="@string/action_settings"
        android:orderInCategory="100"
        app:showAsAction="never" />
</menu>

3.Now we will implement the onCreateOptionsMenu() method  in Activity class and inflate the menu items created in the menu_item.xml. We will also override method OnOptionsItemSelected  for handle the events when user presses the menu option in android.

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.home, 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;
        }
        if(id == R.id.action_search){
       Toast.makeText(getApplicationContext(), "Search action is  selected!" ,                                                   Toast.LENGTH_SHORT).show();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }



1.output screen for three type menu item .



menu item 1 : this is SearchView item and it's :showAsAction="always" it mean this is always show on ActionBar.

menu item2 : this is TextView item and it's showAsAction="ifRoom" it mean this is show in ActionBar if space available on ActionBar otherwise it will open with menu item list as show on image like other menu(three dot).

other menu : this is contain all other menu like howAsAction="never properties menu item as well as showAsAction="ifRoom" item if no space on ActionBar.


2) Context menu

Now we will talk about to create option menu with simple step.

Context Menu is also useful part of application.When we want to open menu in long press of any view class and subClass of android.Context Menu appears when user long press on a View like ListView, GridView etc.

You must to register each view whenever  you want to associated with the context menu.
like this;-
   registerForContextMenu(lv); // lv is a List View

Lets take a exampke.

package com.example.contextmenuapp;

import java.util.ArrayList;
import android.app.ListActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class StudentActivity extends ListActivity
{
ListView lv;
ArrayList<String> list;
ArrayAdapter<String> adp;
@Override
protected void onCreate(Bundle savedInstanceState) {

lv = getListView();
list = new ArrayList<String>();
list.add("Dheeraj");
list.add("Manish");
list.add("Rohan");
list.add("Prakhar");
list.add("Pranav");

adp = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list);
lv.setAdapter(adp);
registerForContextMenu(lv);

super.onCreate(savedInstanceState);
  }
  @Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) 
 {
      menu.add(0,1,0,"Red");
      menu.add(0,2,0,"Green");
      menu.add(0,3,0,"Blue");
 super.onCreateContextMenu(menu, v, menuInfo);
 }
    @Override
    public boolean onContextItemSelected(MenuItem item) 
    {
        int id = item.getItemId();
        AdapterContextMenuInfo minf = (AdapterContextMenuInfo) item.getMenuInfo();
        
            TextView tv = (TextView) minf.targetView;
       switch(id)
 {
 case 1:
 tv.setTextColor(Color.RED);
 break;
 case 2:
 tv.setTextColor(Color.GREEN);
 break;
 case 3:
 tv.setTextColor(Color.BLUE);
 break;
 }
     return super.onContextItemSelected(item);
    }
}

Your screen something like this:- 

after long press on list item 




Thanks You

Android Broadcast Receivers


1. Overview 

Now friends we are going to learn about  Broadcast Receivers
Broadcast Receivers is an android componant which response to broadcast messages from an applications or system itself.Broadcast Receivers will catch specific event from android oprating system, this is happen when wifi on,battery status change,recieved phone calls and cut etc.we can also send Broadcast messages throw intent with the help of "sendBroadcast(intent object)" methos.

there are two way to create Broadcast Receiver

1) static type - registered receiver at AndroidManifest.xml file
2) dynamic type -  registered receiver at dynamically with the help of registered() or unregisterReceiver() methods


2.. How to registered receiver at AndroidManifest.xml file

MyReceiver is a name of Broadcast Receiver

<receiver android:name="MyReceiver">
       <intent-filter>
          <action android:name="com.hello.app"/>
          <category android:name="android.intent.category.DEFAULT"/>
       </intent-filter>
</receiver>

3. Create activity_main.xml layout

In this layout we will take two componant first EditText and second Button.we wiil get some text from EditText and after click on Button send broadcast message

<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" >
   <EditText
      android:id="@+id/editText1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentLeft="true"
      android:layout_alignParentTop="true"
      android:layout_marginLeft="44dp"
      android:layout_marginTop="26dp"
      android:ems="10" >
    <requestFocus />
  </EditText>
  <Button 
   android:id="@+id/button1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_alignLeft="@+id/editText1"
   android:layout_below="@+id/editText1"
   android:layout_marginTop="32dp"
   android:text="Send Signal" />
</RelativeLayout>


4.How to create  Broadcast  sender

send Broadcast message by sendBriadcast method

package com.example.broadcastsenderapp;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {

EditText et;
Button bt;

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_main);
          et = (EditText) findViewById(R.id.editText1);
          bt = (Button) findViewById(R.id.button1);
       bt.setOnClickListener(new OnClickListener()
       {
            @Override
            public void onClick(View v)
            {
                   String data = et.getText().toString();
                   Intent in = new Intent("com.hello.app");
                   in.putExtra("data",data);
                   sendBroadcast(in);
            }
       });
    }
    @Override
       public boolean onCreateOptionsMenu(Menu menu) {
       // Inflate the menu; this adds items to the action bar if it is present.
          getMenuInflater().inflate(R.menu.main, menu);
        return true;
       }
  }

3.Create Broadcast Receiver

here  receive message by intent

package com.example.broadcastsenderapp;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context arg0, Intent in)
   {
        String data = in.getStringExtra("data");
        Toast.makeText(arg0, data, 2).show();
    }
}


if you have any issue and want to know more about Broadcast receiver please comments on blow comments box.

Thanks..