Android Menus: part 3: Context Menus
In previous posts we explored two types of android menus: Options menu and submenus. In this post we’re going to see another menu type: Context menus.
Context Menu:
Context menus are the menus that appear when you right-click in windows.
In android Context menu are attached to widgets and the appear when you click on the widget for a long time (long click).
To add context menus to widgets you have to do two things:
Then we add items to the context menu by overriding the onCreateContext method:
The onCreateContextMenu method has the following parameters:
We do it the same way we handle onOptionsItemSelected.
Context Menu:
Context menus are the menus that appear when you right-click in windows.
In android Context menu are attached to widgets and the appear when you click on the widget for a long time (long click).
To add context menus to widgets you have to do two things:
- Register the widget for a context menu.
- Add menu items to the context menu.
@OverrideWe call registerForContextMenu(View V) method to tell the activity that the view is going to have a context menu.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txt=(TextView)findViewById(R.id.txt);
registerForContextMenu(txt);
}
Then we add items to the context menu by overriding the onCreateContext method:
@OverrideWhen you make a long click on the text view the context menu will appear like this:
public void onCreateContextMenu(ContextMenu menu,View v,ContextMenuInfo info)
{
menu.setHeaderTitle("Context Menu");
menu.add("Item");
}
The onCreateContextMenu method has the following parameters:
- Context Menu: an instance of the context menu.
- View: the view to which the context menu is attached.
- ContextMenuInfo: carries additional information regarding the creation of the context menu.
We do it the same way we handle onOptionsItemSelected.
@Override
public boolean onContextItemSelected(MenuItem item)
{
txt.setText(item.getTitle());
return true;
}
No comments: