Dynamic Menu in Android? - android

I need to show menu at the time of button Click.But I am not able to display the menu . My code is below. Can anyone tell me what is wrong in my code ??? Thanks in Advance !!!
Code :
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class DynamicMenu extends Activity {
/** Called when the activity is first created. */
private Context context;
Button btnMenu;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
LinearLayout llay = new LinearLayout(context);
btnMenu = new Button(context);
btnMenu.setText("Show Menu");
llay.addView(btnMenu);
setContentView(llay);
registerForContextMenu(btnMenu);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
Menu m_menu = menu;
m_menu.add(0, 1, 0, "Settings");
m_menu.add(0, 2, 0, "About");
m_menu.add(0, 3, 0, "Exit");
}
}

What do you want to call ? Menu or Context Menu these are two diffrent things.
What you have coded causes a Context Menu to appear. (Long click the button to show the context menu) , heres a sample:
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
public class MenuDemo extends Activity {
/** Called when the activity is first created. */
private Context context;
Button btnMenu;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
LinearLayout llay = new LinearLayout(context);
btnMenu = new Button(context);
btnMenu.setText("Show Menu");
llay.addView(btnMenu);
setContentView(llay);
registerForContextMenu(btnMenu);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo) {//Context Menu that appears when long clicked.
Menu m_menu = menu;
m_menu.add(Menu.NONE, Menu.FIRST+1, 0, "Settings");
m_menu.add(Menu.NONE, Menu.FIRST+2, 0, "About");
m_menu.add(Menu.NONE, Menu.FIRST+3, 0, "Exit");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//Menu that appears when menu button is pressed on device
Menu m_menu = menu;
m_menu.add(Menu.NONE, Menu.FIRST+3, 0, "Settings");
m_menu.add(Menu.NONE, Menu.FIRST+4, 0, "About");
m_menu.add(Menu.NONE, Menu.FIRST+5, 0, "Exit");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
String msg="Selected from menu: ";
switch (item.getItemId()){
case Menu.FIRST+3:
Toast.makeText(this, msg+"Settings Menu", Toast.LENGTH_LONG).show();
return true;
case Menu.FIRST+4:
Toast.makeText(this, msg+"About Menu", Toast.LENGTH_LONG).show();
return true;
case Menu.FIRST+5:
Toast.makeText(this, msg+"Exit Menu", Toast.LENGTH_LONG).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
String msg="Selected from context menu: ";
switch (item.getItemId()){
case Menu.FIRST+1:
Toast.makeText(this, msg+"Settings", Toast.LENGTH_LONG).show();
return true;
case Menu.FIRST+2:
Toast.makeText(this, msg+"About", Toast.LENGTH_LONG).show();
return true;
case Menu.FIRST+3:
Toast.makeText(this, msg+"Exit", Toast.LENGTH_LONG).show();
return true;
}
return super.onContextItemSelected(item);
}
}
This is not the best practiced and recommended code you can really make use of polymorphism here. But I hope this gives you an idea.

When i use the following code i can able to get the menu at the time of button click
registerForContextMenu(btnMenu);
btnMenu.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((DynamicMenu) context).openContextMenu(btnMenu);
}
});
Thanks to all.

In the onCreateContextMenu you are not calling the super class constructor. You can refer that from http://developer.android.com/guide/topics/ui/menus.html
Something like this super.onCreateContextMenu(menu, v, menuInfo);

Related

Error why working contextual action mode start ActionModeis not applicable for the arguments (ActionMode

I am following a tutorial 11. Exercise: Using the contextual action mode
But I am having this error :
mActionMode = Display.this.startActionMode(mActionModeCallback);
view.setSelected(true);
Error: The method startActionMode(ActionMode.Callback) in the type Activity is not applicable for the arguments (ActionMode.Callback)
I checked this stackoverflow answer
they said to add
ActionBarActivity activity=(ActionBarActivity)getActivity();
activity.startSupportActionMode(modeCallBack);
I had this error
The method getActivity() is undefined for the type Display
what I am doing wrong ? the below is my code.
package com.example.sqlfirst;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.Tab;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.view.ActionMode;
import android.view.ActionMode.Callback;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
public class Display extends ActionBarActivity {
private final static String TAG = "MainActivity";
protected Object mActionMode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_main);
//have to use getSupportActionBar from android.support.v7.app
// ActionBar actionBar = getSupportActionBar();
//getActionBar().setDisplayHomeAsUpEnabled(true);
ActionBarActivity activity=(ActionBarActivity)getActivity();
activity.startSupportActionMode(modeCallBack);
View view = findViewById(R.id.gridview);
view.setOnLongClickListener(new View.OnLongClickListener() {
// called when the user long-clicks on someView
public boolean onLongClick(View view) {
if (mActionMode != null) {
return false;
}
// start the CAB using the ActionMode.Callback defined above
mActionMode = Display.this.startActionMode(mActionModeCallback);
view.setSelected(true);
return true;
}
});
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// Send intent to SingleViewActivity
Intent i = new Intent(getApplicationContext(), SingleViewActivity.class);
// Pass image index
i.putExtra("id", position);
startActivity(i);
} });
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main_actions, menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item)
{
super.onOptionsItemSelected(item);
switch (item.getItemId()){
case R.id.ic_action_person:
Toast.makeText(this, "Create a new account please", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, Register.class);
startActivity(intent);
return true;
case R.id.ic_action_search:
Toast.makeText(this, "Search for new images", Toast.LENGTH_SHORT).show();
Intent isearch= new Intent(this,Search.class);
startActivity(isearch);
return true;
case R.id.ic_action_picture:
Toast.makeText(this, "Search for new photos", Toast.LENGTH_SHORT).show();
Intent iphotos= new Intent(this,Display.class);
startActivity(iphotos);
return true;
}
return true;
}
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
// Called when the action mode is created; startActionMode() was called
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// inflate a menu resource providing context menu items
MenuInflater inflater = mode.getMenuInflater();
// assumes that you have "contexual.xml" menu resources
inflater.inflate(R.menu.activity_main_actions, menu);
return true;
}
// called each time the action mode is shown. Always called after
// onCreateActionMode, but
// may be called multiple times if the mode is invalidated.
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false; // Return false if nothing is done
}
// called when the user selects a contextual menu item
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.ic_action_picture:
Toast.makeText(Display.this, "Selected menu",
Toast.LENGTH_LONG).show();
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}
// called when the user exits the action mode
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
}
};
}
Your Display class is extending ActionBarActivity, that means that it´s an Activity so there´s no need to use getActivity(), you can directly make use of the methods like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* this method is available within your ActionBarActivity*/
startSupportActionMode(modeCallBack);
setContentView(R.layout.grid_main);
// The rest of your code comes here
}

Contextual action bar not showing sellection

I'm trying to implement a Contextual Action Bar (CAB) but whenever I long click an item it is not showing the item as selected (highlighted) so I'm not able to select multiple items to batch delete either. Below is the fragment attempting to utilize a CAB.
package com.garciaericn.memoryvault.main;
import android.app.Fragment;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.garciaericn.memoryvault.R;
import com.garciaericn.memoryvault.data.Memory;
import com.garciaericn.memoryvault.data.MemoryAdapter;
import com.parse.DeleteCallback;
import com.parse.FindCallback;
import com.parse.ParseException;
import java.util.List;
public class MemoriesFragment extends Fragment implements AbsListView.MultiChoiceModeListener, AdapterView.OnItemClickListener {
ListView memoriesListView;
MemoryAdapter memoryAdapter;
public MemoriesFragment() {
// Mandatory empty constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
memoryAdapter = new MemoryAdapter(getActivity());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_memories, container);
memoriesListView = (ListView) view.findViewById(R.id.listView);
memoriesListView.setAdapter(memoryAdapter);
memoriesListView.setOnItemClickListener(this);
memoriesListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
memoriesListView.setMultiChoiceModeListener(this);
return view;
}
private void refreshMemories() {
Memory.getQuery().findInBackground(new FindCallback<Memory>() {
#Override
public void done(List<Memory> memoryList, ParseException e) {
memoryAdapter.loadObjects();
}
});
}
#Override
public void onStart() {
super.onStart();
refreshMemories();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_sync: {
refreshMemories();
Toast.makeText(getActivity(), "Refreshed from fragment", Toast.LENGTH_SHORT).show();
return true;
}
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
// Here you can do something when items are selected/de-selected,
// such as update the title in the CAB
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.action_delete:
Toast.makeText(getActivity(), "Delete!", Toast.LENGTH_SHORT).show();
// TODO: Delete item
mode.finish(); // Action picked, so close the CAB
return true;
}
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
// Here you can make any necessary updates to the activity when
// the CAB is removed. By default, selected items are deselected/unchecked.
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Memory memory = memoryAdapter.getItem(position);
/*// Un-comment to delete item
memory.deleteInBackground(new DeleteCallback() {
#Override
public void done(ParseException e) {
refreshMemories();
}
});
*/
Toast.makeText(getActivity(), memory.toString() + " was tapped", Toast.LENGTH_SHORT).show();
}
}
If you are implementing custom adapter you need to implement Checkable layout for listview item.
Check this Github page
which explains implementation of Checkable layout with demo adapter.
Use in in your custom list item layout like:
<your.package.CheckableLayout ... />
-Hey correct me if i am wrong I found in your code that you are implementing OnItemClickListener instead use AdapterView.OnItemLongClickListener as you wants you action on Long Click item.

onContextItemSelected is not called in Fragment

I'm trying use the popup menu in long press in ListView. I can call the popup menu, but when i click in the option of this popup menu the onContextItemSelected() not works.
Here is my code:
package com.pa.homeautomationblank.fragments;
import android.app.Fragment;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.pa.homeautomationblank.R;
import com.pa.homeautomationblank.listeners.OnItemCentraisLongClickListener;
import com.pa.homeautomationblank.listeners.OnReconhecerCentraisClickListener;
import com.pa.homeautomationblank.model.Central;
import com.pa.homeautomationblank.model.dao.CentralDAO;
public class CentraisFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.fragment_centrais, container,false);
RelativeLayout rLay = (RelativeLayout) view.findViewById(R.id.layout_centrais_bottom);
Button btnReconhecerCentrais = (Button) rLay.findViewById(R.id.btnReconhecerCentrais);
btnReconhecerCentrais.setOnClickListener(new OnReconhecerCentraisClickListener());
CentralDAO cDAO = new CentralDAO(view.getContext());
ArrayAdapter<Central> adapter = new ArrayAdapter<Central>(view.getContext(), android.R.layout.simple_list_item_1 , cDAO.selectAll());
rLay = (RelativeLayout) view.findViewById(R.id.layout_centrais_conteudo);
ListView lv = (ListView) rLay.findViewById(R.id.lvCentrais);
lv.setAdapter(adapter);
lv.setOnItemLongClickListener(new OnItemCentraisLongClickListener());
registerForContextMenu(lv);
return (view);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo){
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId()==R.id.lvCentrais){
menu.setHeaderTitle(R.string.operacoes);
String[] menuitems = getResources().getStringArray(R.array.menu_acoes_central);
for (int i=0;i<menuitems.length;i++){
menu.add(Menu.NONE,i,i,menuitems[i]);
}
}
}
#Override
public boolean onContextItemSelected(MenuItem item){
int menuindex = item.getItemId();
switch (menuindex) {
case 0:
Toast.makeText(getView().getContext(), "Rename", Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(getView().getContext(), "Remove", Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(getView().getContext(), "invalid option!", Toast.LENGTH_SHORT).show();
break;
}
return super.onContextItemSelected(item);
}
}
I put breakpoint in the method but the event is not called.
Thanks in advance!
For anybody still looking for a workaround, Once I solved this issue by creating an anonymous OnMenuItemClickListener that delegates back to onContextItemSelected(MenuItem item) and setting it on all the items in my menu.
#Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
// Creation/inflate menu here
OnMenuItemClickListener listener = new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
onContextItemSelected(item);
return true;
}
};
for (int i = 0, n = menu.size(); i < n; i++)
menu.getItem(i).setOnMenuItemClickListener(listener);
}
I solved my problem.
I change the implementation of this method: onContextItemSelected to setOnMenuItemClickListener inside of onCreateContextMenu method as the following code:
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo){
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId()==R.id.lvCentrais){
menu.setHeaderTitle(R.string.operacoes);
String[] menuitems = getResources().getStringArray(R.array.menu_acoes_central);
for (int i=0;i<menuitems.length;i++){
menu.add(Menu.NONE,i,i,menuitems[i]);
}
for (int i=0;i<menu.size();i++){
menu.getItem(i).setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
int menuindex = item.getItemId();
switch (menuindex) {
case 0:
Toast.makeText(getView().getContext(), "Rename", Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(getView().getContext(), "Remove", Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(getView().getContext(), "invalid option!", Toast.LENGTH_SHORT).show();
break;
}
return false;
}
});
}
}
}
Thanks for all help!

Open pop up after clicking android menu item

I want to open pop up or dialog box after clicking on menu item. I have written the code but the dialog box is not opening. The menu has two items "about" and "help". Is there any other way to show pop up message.?
Here is my code:
package com.easy.convert;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class AndroidMenusActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// Initiating Menu XML file (menu.xml)
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
return true;
}
/**
* Event Handling for Individual menu item selected
* Identify single menu item by it's id
* */
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.menu_help:
Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.aboutus);
dialog.setTitle("Help");
dialog.setCancelable(true);
dialog.show();
return true;
case R.id.menu_about:
Dialog dialog1 = new Dialog(this);
dialog1.setContentView(R.layout.aboutus);
dialog1.setTitle("About");
dialog1.setCancelable(true);
dialog1.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

how to create option menus in android application [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Android, How to create option Menu
i have tried all the things but i am not able to create option menus.can u please give me full code for that ? should i make any changes in manifest file to create menus ? should i create another class only for menu or i can write it in any class created before ? please help me.can i write like this :
package com.example.FirstProject;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
//import android.widget.EditText;
//import android.widget.RadioButton;
//import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
public class FirstProjectActivity extends Activity {
/** Called when the activity is first created. */
protected ListAdapter adapter;
Cursor cursor;
protected String[] cities = {"Mumbai"};
ListView lv ;
ListView stations;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void myClickHandler(View view)
{
Intent i=new Intent(this,City.class);
startActivity(i);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
{
if( R.id.icon==item.getItemId()) Toast.makeText(this, "You pressed the icon!", Toast.LENGTH_LONG).show();
if( R.id.icon==item.getItemId()) Toast.makeText(this, "You pressed the text!", Toast.LENGTH_LONG).show();
if( R.id.icon==item.getItemId()) Toast.makeText(this, "You pressed the icon and text!", Toast.LENGTH_LONG).show();
}
return true;
}
}
Use code like below:
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
menu.add("Item1");
menu.add("Item2");
return true;
}
try with this...
public boolean onOptionsItemSelected(MenuItem item)
{
System.out.println("entered to option selected");
switch(item.getItemId())
{
case R.id.icon:
System.out.println("entered to icon");
Toast.makeText(this, "icon clicked", Toast.LENGTH_LONG).show();
break;
case R.id.text:
Toast.makeText(this, "text clicked", Toast.LENGTH_LONG).show();
break;
case R.id.iconandtext:
Toast.makeText(this, "icon and text clicked", Toast.LENGTH_LONG).show();
break;
}
return true;
}
refer this link.. also it will be usefull enter link description here
You can use the following code inside the menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/menu1"
android:alphabeticShortcut="s"
android:title="menu1 title"
/>
<item
android:id="#+id/menu2"
android:alphabeticShortcut="t"
android:title="menu2 title"
/>
</menu>
now the two methods for the invoking the menu and function which is to be called on the item selected.
#override
public boolean onCreateOptionsMenu (Menu menu){
super.onCreateOptionsMenu(menu);
//menu.add(R.menu.main_menu);
//menu.add(Menu.NONE, 101,Menu.FIRST,this.getResources().getString(R.string.Title));
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.main_menu, menu);
return true;
}
you can use the both the method of invoking the menu. First one by the menu.add and second one by the inflating the menu.xml file
Now on the itemselectedlistner is used by the following code
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.menu1:
// your code here
case R.id.menu2:
// your code here
}
return false;
}
just pass the id in switch-case and do whatever you want by selecting the those menu.

Categories

Resources