I have made a simple app that just brings up an AlertDialog, with four items in the list. I register a context menu. When I long click one of the items, I get the context menu. I then select an item from the context menu, but onContextItemSelected never gets called. Any help? Thanks.
test.java:
package com.cerulean.tech.creations.test;
import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
public class test extends Activity {
private String[] files;
AlertDialog alert;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
files = new String[4];
}
public void selectScheme(View v) {
files[0] = "<New Scheme>";
files[1] = "test1";
files[2] = "test2";
files[3] = "test3";
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setItems(files, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
}});
alert = builder.create();
alert.show();
registerForContextMenu(alert.getListView());
}
#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, "Delete");
menu.add(0, v.getId(), 0, "Cancel");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
return false;
}
}
In main.xml, I just a button defined with android:onClick="selectScheme"
After this line:
registerForContextMenu(alert.getListView());
type this:
alert.getListView().setOnCreateContextMenuListener(this);
And instead of onContextItemSelected(MenuItem item) function use this:
#Override
public boolean onMenuItemSelected(int featureId, MenuItem menuItem) {
The following function always gets executed.
public boolean onMenuItemSelected(int featureId, MenuItem menuItem)
But you can differentiate between context menus and option menus using the following flags:
if (featureId == Window.FEATURE_CONTEXT_MENU)
{
//Do something
}
else if (featureId == Window.FEATURE_OPTIONS_PANEL)
{
//Do something else
}
Just Add
#Override
public boolean onMenuItemSelected(int aFeatureId, MenuItem aMenuItem) {
if (aFeatureId==Window.FEATURE_CONTEXT_MENU)
return onContextItemSelected(aMenuItem);
else
return super.onMenuItemSelected(aFeatureId, aMenuItem);
}
I want to build on Miki's answer.
I only used
registerForContextMenu(this.getListView());
and
this.getListView().setOnCreateContextMenuListener(this);
in my parent ListActivity class.
I moved my code from the onContextItemSelected(MenuItem item) method to the onMenuItemSelected method.
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
try {
if (item.getItemId() == R.id.new_entry_menu_option) {
...
}
...
if (item.getItemId() == R.id.quit) {
/* perform cleanup */
...
return true;
} else if (item.getItemId() == R.id.delete_entry_context_menu_option) {
displayConfirmRequest(DELETE_CONFIRMATION_MESSAGE, item);
return true;
} else if (item.getItemId() == R.id.2ND_CONTEXT_OPTION) {
//code for 2nd option
return true;
} else if (item.getItemId() == R.id.3RD_CONTEXT_OPTION) {
//code for 3RD option
return true;
} else {
return super.onMenuItemSelected(featureId, item);
}// end if/else if/else
}// end try
catch (Exception error) {
//error handler code
return false;
}// end try/catch
}// end onMenuItemSelected
And make sure in your subclass, if you override onMenuItemSelected in the subclass of your super.ListActivity class, to include the following code if you want the contextmenu options to be handled in the super.class.
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
if (<condition>) {
...
} else {
return super.onMenuItemSelected(featureId, item);
}
}// end onMenuItemSelected
The real cause of this problem is that you're overriding onContextItemSelected and not calling super.onContextItemSelected. Change your onContextItemSelected method to this:
#Override
public boolean onContextItemSelected(MenuItem item) {
if (super.onContextItemSelected(MenuItem item))
return true;
return false;
}
Related
I'm trying to make a toast on item selected but it's showing unreachable statement error.
My code is:
btn=(Button)findViewById(R.id.button);
btn.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
btn.performLongClick();
}
}
);
registerForContextMenu(btn);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("For Optimum Results");
menu.add(0,v.getId(),0,"Hi");
menu.add(0,v.getId(),0,"Hello");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
return super.onContextItemSelected(item);
if(item.getTitle()=="Hi"){
Toast.makeText(this,"hi",Toast.LENGTH_SHORT).show();
}
return true;
}
you have two type of error:
1)return super (return super.onContextItemSelected(item)) , it means that you return your method at first line so lines below not execute.
2)wrong comparing String (item.getTitle()=="Hi")
correct code should be like this:
#Override
public boolean onContextItemSelected(MenuItem item) {
//return super.onContextItemSelected(item);//remove this line
if(item.getTitle().equal("Hi")){// also maybe you want to check not null for item.getTitle()
Toast.makeText(this,"hi",Toast.LENGTH_SHORT).show();
}
return true;
}
public class MainActivity extends AppCompatActivity {
private final int item_4 = 4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onPrepareOptionsMenu();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.menu_main, menu);
menu.add(Menu.NONE, item_4, Menu.NONE, "Show");
menu.add(Menu.NONE, item_4, Menu.NONE, "Hide");
menu.add("Reset");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item1:
Toast.makeText(this, "You Pressed Settings", Toast.LENGTH_SHORT).show();
return true;
case R.id.item2:
Toast.makeText(this, "You Pressed Create", Toast.LENGTH_SHORT).show();
return true;
case R.id.item3:
Toast.makeText(this, "You Pressed Delete", Toast.LENGTH_SHORT).show();
return true;
case item_4:
Toast.makeText(this, "You Pressed Hide", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem mii = menu.findItem(R.id.item2);
mii.setEnabled(false);
return super.onPrepareOptionsMenu(menu);
}
}
In the above code I have created a menu item list for the app bar and I have created a button in my app and i want some of my items to be disabled after button click but I am not able to do so as I am not gettig how to call onPrepareOptionsMenu() on button click? Can anyone suggest a solution for how to disable the menu items after button click?
I will show short example:
Only one note for this method: don’t forget to clear menu items (menu.clear();) on every method start.
Example:
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/**
* Class which shows how to change dynamically options menu items
*/
public class Main extends Activity {
private Button clickBtn;
private boolean isChangedStat = false;
private static final int MENUITEM = Menu.FIRST;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
clickBtn = (Button) findViewById(R.id.click);
clickBtn.setText("Click me");
clickBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(isChangedStat) {
isChangedStat = false;
} else {
isChangedStat = true;
}
}
});
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear();
if(isChangedStat) {
menu.add(0, MENUITEM, 0, "True");
} else {
menu.add(0, MENUITEM, 0, "False");
}
return super.onPrepareOptionsMenu(menu);
}
}
Reference from:
Android: How to enable/disable option menu item on button click?
Once the activity is created, the onCreateOptionsMenu() method is
called only once, as described above. The system keeps and re-uses the
Menu you define in this method until your activity is destroyed. If
you want to change the Options Menu any time after it's first created,
you must override the onPrepareOptionsMenu() method. This passes you
the Menu object as it currently exists. This is useful if you'd like
to remove, add, disable, or enable menu items depending on the current
state of your application.
you could call the method invalidateOptionsMenu(); in your button's click listener. It will call onPrepareOptionsMenu() again, all your logic to disable could be written here.
Anyway, documents covers all.
I am adding a menu item for texts selection. normally it shows cut,copy,share, etc.. I added a one more item to this menu and named the item as "Mark".
For this I added the following code in my Activity.Java
#Override
public void onActionModeStarted(ActionMode mode) {
if (mActionMode == null) {
mActionMode = mode;
Menu menu = mode.getMenu();
menu.add("Mark");
mode.getMenuInflater().inflate(R.menu.main, menu);
}
super.onActionModeStarted(mode);
}
I am able to get my menu item while long press on texts.. Below is the screen, which reflects my menu item.
For this menu item, I want to do something while select it. So, I used the following code.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if( item.getTitle().equals("Mark")){
System.out.println("MenuItem Mark clicked----");
Log.d("MenuItem clicked----", "Mark");
}
return super.onOptionsItemSelected(item);
}
Here, I am not able to get the message "MenuItem Mark clicked----" or "MenuItem clicked---- Mark" in my Logcat.
How may I do this?
update
Followed Elitz's answer, but still no luck. my Changes below
#Override
public void onActionModeStarted(ActionMode mode) {
if (mActionMode == null) {
mActionMode = mode;
Menu menu = mode.getMenu();
menu.add(0,1000,0,"Mark");
mode.getMenuInflater().inflate(R.menu.main, menu);
}
super.onActionModeStarted(mode);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == 1000) {
System.out.println("MenuItem Mark clicked----");
Log.d("MenuItem clicked----", "Mark");
}
return super.onOptionsItemSelected(item);
}
Added updated answer and still no messages came in Logcat
private ActionMode.Callback startActionMode = (new ActionMode.Callback() {
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu yourMenu) {
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu yourMenu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem yourMenu) {
Log.d("MenuItem clicked----303", "Mark");
if (yourMenu.getItemId() == R.attr.actionModeSelectAllDrawable) {
System.out.println("MenuItem Mark clicked----305");
Log.d("MenuItem clicked----", "Mark");
}
return true;
}
});
update2
Followed Ankesh's answer also,
#Override
public void onActionModeStarted(ActionMode mode) {
if (mActionMode == null) {
mActionMode = mode;
Menu menu = mode.getMenu();
menu.add(R.id.privateText);
mode.getMenuInflater().inflate(R.menu.main, menu);
}
super.onActionModeStarted(mode);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.privateText) {
System.out.println("MenuItem Mark clicked----");
Log.d("MenuItem clicked----", "Mark");
}
return super.onOptionsItemSelected(item);
}
Both attempt there is no logs available...
Update3
For test the other menu, I found id for selectAll menu item in R,java, and tried the following code,
#Override
public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.attr.actionModeSelectAllDrawable) {
System.out.println("MenuItem All clicked----");
Log.d("MenuItem clicked----", "All");
}
return super.onOptionsItemSelected(item);
}
this is also not showing the message in Logcat. Is this function is right one for menu items selection. or what else I am missing in this?
use this instead of your menu.add("Mark");
add(int groupId, int itemId, int order, CharSequence title);
now you have your Id now you can check for that.
groupId = 0; and order = 0;, or any number that fits your choice, but since in your example you have only 1 group, just put 0.
hmm.. i think you got us all fooled :) yes it will not work, because you are using ActionMode right and with ActionMode you need to specify a callback for it, so you should put your code here
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem arg1) {
return false;
}
in its callback. like something like this, when you call startActoinMode
startActionMode(new ActionMode.Callback() {
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu yourMenu) {
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu yourMenu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem yourMenu) {
//put your item click here
return false;
}
});
Use
if (item.getItemId() == R.id.xyz) {
}
Can you just add your menu item inside your xml menu(I mean inside R.menu.main)? And after that just detect the item click inside this method:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_id:
//TODO click detected!!
break
default:
return super.onOptionsItemSelected(item);
}
}
Its that or I don't understand your question :)
i am using onCreateOptionsItem as shown below in the code, but when i overide onMenuItemSelected, it is marked with red. is there an alternative to it?how
can i fix this errors
code:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem miRefrsh = menu.add(0, 1, 0,"refresh");
miRefrsh.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
//进入关于页面
MenuItem miScan = menu.add(0, 2, 1, "scan");
miScan.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
//退出系统
MenuItem miCancel = menu.add(0, 3, 2, "cancel");
miCancel.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
MenuItem miExit = menu.add(0, 4, 2, "exit");
miExit.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
return super.onCreateOptionsMenu(menu);
}
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId()) {
case MEMU_RESCAN:
this.mGP.closeConn();
this.initActivityView();
this.openDiscovery();
return true;
case MEMU_EXIT:
this.finish();
return true;
case MEMU_ABOUT:
this.openAbout();
return true;
default:
return super.onMenuItemSelected(featureId, item);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// do Your Work Here
return super.onOptionsItemSelected(item);
}
Android knows about several types of menus (e.g. Options Menu and Context Menu). ''onMenuItemSelected'' is the generic callback. You don't need to use this usually. ''onOptionsItemSelected'' is the callback of the options menu and onContextItemSelected is the callback of the context menu.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) { //or switch-case
finish();
}
if (id == R.id.your_item1) {
}
if (id == R.id.your_item2) {
}
return super.onOptionsItemSelected(item);
}
SUDARSHAN is right. you can use onOptionsItemSelected.
use onOptionsItemSelected(MenuItem item) method and extend AppCompatActivity
In your case you should use menuItem.getTitle() and compare to the titles you programmatically added previously. Use menuItem.getId online when you're inflating a XML menu file. Hope this helps
I have set setOnCreateContextMenuListener to edittext. onCreateContextMenu method is called user long press on edittext. and it opens context menu with 'done' and 'copy' options.
But my question is how can I handle when user select done option or copy options?
Can I get any event when user click on done button or copy button. so I can get selected text via clip manager?
edit.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
Log.i("TAG", "onCreateContextMenu");//it is printing while context menu is created.
}
});
Thanks.
onContextItemSelected is the event you should use. but it has no View argument to access selected item. Here is a trick to access to selected View.
public class MainActivity extends Activity
{
protected View selectedView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv = (ListView)findViewById(R.id.lv1);
registerForContextMenu(lv);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
{
this.selectedView = v;
super.onCreateContextMenu(menu, v, menuInfo);
}
#Override
public boolean onContextItemSelected(MenuItem item)
{
switch(item.getId())
{
case R.id.Context_Edit:
// access to view with this.selectedView
break;
case R.id.Context_Delete:
// access to view with this.selectedView
break;
default:
return super.onContextItemSelected(item);
}
return true;
}
}
You can get your both button event like following example
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv = (ListView)findViewById(R.id.lv1);
registerForContextMenu(lv);
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId() == R.id.lv1)
{
menu.setHeaderTitle("Select Action");
menu.add(0, v.getId(), 0, "Edit");
menu.add(0, v.getId(), 0, "Delete");
}
}
#Override
public boolean onContextItemSelected(MenuItem item)
{
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
if(item.getTitle() == "Edit")
{
// do something
}
if(item.getTitle() == "Delete")
{
// do something
}
return true;
}
Hope it will help you.
You must to override the onLongClick of the editText and setting one CAB. This is example:
private ActionMode.Callback action = new ActionMode.Callback() {
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
// TODO Auto-generated method stub
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
if (item.getItemId() == android.R.id.copy){
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
Log.i("CAB",String.valueOf(clipboard.getPrimaryClip().getItemAt(0).getText()));
}
return true;
}
};
private EditText edtText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtText = (EditText) findViewById(R.id.edtText1);
registerForContextMenu(edtText);
edtText.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
((EditText)v).setTextIsSelectable(true);
((EditText)v).setCustomSelectionActionModeCallback(action);
return false;
}
});
}