Context Menu(Long press menu)
We then use registerForContextMenu in the onCreate of the activity to tell android that we want this view to create a menu when it is long pressed. This is not limited to buttons, this will work for other views too. You must register each view that you want to have associated with the context menu.
1, Then register menu and button in onCreate method
bt=(Button) findViewById(R.id.bt1);
registerForContextMenu(bt);
2, Override the onCreateContextMenu method to create the menu:
@Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Context Menu");
menu.add(0, v.getId(), 0, "Action 1");
menu.add(0, v.getId(), 0, "Action 2");
}
4,Then override onContextItemSelected to preform the action when an option is selected from this menu:
@Override
public boolean onContextItemSelected(MenuItem item)
{
if(item.getTitle()=="Action 1")
{
function1(item.getItemId());
}
else if(item.getTitle()=="Action 2")
{
function2(item.getItemId());
}
else
{
return false;
}
return true;
}
private void function1(int itemId)
{
Toast.makeText(this, "function 1 called", Toast.LENGTH_SHORT).show();
}
private void function2(int itemId)
{
Toast.makeText(this, "function 2 called", Toast.LENGTH_SHORT).show();
}
}
We then use registerForContextMenu in the onCreate of the activity to tell android that we want this view to create a menu when it is long pressed. This is not limited to buttons, this will work for other views too. You must register each view that you want to have associated with the context menu.
1, Then register menu and button in onCreate method
bt=(Button) findViewById(R.id.bt1);
registerForContextMenu(bt);
2, Override the onCreateContextMenu method to create the menu:
@Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Context Menu");
menu.add(0, v.getId(), 0, "Action 1");
menu.add(0, v.getId(), 0, "Action 2");
}
4,Then override onContextItemSelected to preform the action when an option is selected from this menu:
@Override
public boolean onContextItemSelected(MenuItem item)
{
if(item.getTitle()=="Action 1")
{
function1(item.getItemId());
}
else if(item.getTitle()=="Action 2")
{
function2(item.getItemId());
}
else
{
return false;
}
return true;
}
private void function1(int itemId)
{
Toast.makeText(this, "function 1 called", Toast.LENGTH_SHORT).show();
}
private void function2(int itemId)
{
Toast.makeText(this, "function 2 called", Toast.LENGTH_SHORT).show();
}
}
No comments :
Post a Comment