In the previous post we learnt what an Option Menu was, in
this post we will get to know how to create Context Menu. This menu appears
only when a user holds the screen for a considerable period of time.
To
create a Context menu, I have created a button which has been registered for
context menu. When you click on this button a context menu opens up which will
have 2 options called ‘Go to Action1’ and ‘Go to Action2’. Based on the user selection one of the
options, the action1 or action 2 will start.
So Create a layout Main.xml and add a Textview on top which
will show the application name. Then Create a button which we will use for
invoking the context menu. The main.xml file will look like as shown below.
Create 2 xml files in the layouts which will be for Action1
and Action2. These will have a textview which will have Action1/Action2. Then
there will be a button which will take it back to the main screen. Given below
is how Action1 will look like, Action2 can be created on similar lines.
Then open the main java file under src folder. First Create
a button and bind it to the id. Then register this button for context menu in
the view as shown below.
Button B1=(Button)
findViewById(R.id.button1);
this.registerForContextMenu(B1);
Once you do this you need to populate all the items in the
context menu. This can be achieved by the one below
public void onCreateContextMenu(ContextMenu menu, View
v,ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu,
v, menuInfo);
menu.setHeaderTitle("Context
Menu Options");
menu.add(0,1,0,"Go
To Action1");
menu.add(0,2,0,"Go
To Action2");
}
After you have added all the menu items, you need to
associate activity with each of the items, this can be achieved by the code
below –
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()){
case
0: Intent Action1=new
Intent(this,Action1.class);
this.startActivity(Action1);
break;
case
1: Intent Action2=new
Intent(this,Action2.class);
this.startActivity(Action2);
break;
default:break;
}
return
true;
}
At the end the file will look as shown below –
As you can see we have associated Activity with each of the
menu item. So we need to create 2 class called Activity1 and Activity2 which
will have code which returns back to the main screen as shown below.
Now Right click on the project and say Run As – Android Application.
When you touch and hold on the button, the context menu should appear as shown
in the image below.
Click on Action1 and it should take you to the screen as
shown below and when you click on the ‘Go back to Main Screen’ then it should
take you back to the original screen.
Great explanation.
ReplyDeleteVery helpful to me.
Thanks a lot