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!
Related
I require to create a button in my layout which on pressing displays a list below it and on repressing it the list should disappear ? How can i do this?
This kind of list is popup menu or context menu.
import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.TextView;
import android.widget.Toast;
public class MyLovelyClass extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lovely_layout);
//get a reference to the view for pressing
TextView pressView = (TextView)findViewById(R.id.press);
//register it for context
registerForContextMenu(pressView);
}
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.lovely_context, menu);
}
public boolean onContextItemSelected(MenuItem item) {
//find out which menu item was pressed
switch (item.getItemId()) {
case R.id.option1:
doOptionOne();
return true;
case R.id.option2:
doOptionTwo();
return true;
default:
return false;
}
}
private void doOptionOne() {
Toast.makeText(this, "Option One Chosen...", Toast.LENGTH_LONG).show();
}
private void doOptionTwo() {
Toast.makeText(this, "Option Two Chosen...", Toast.LENGTH_LONG).show();
}
}
Or in ListFragment you can use this example
#Override
public void onCreateContextMenu(final ContextMenu menu, final View v,
final ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
final StartConversationActivity activity = (StartConversationActivity) getActivity();
activity.getMenuInflater().inflate(mResContextMenu, menu);
final AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
if (mResContextMenu == R.menu.conference_context) {
activity.conference_context_id = acmi.position;
} else if (mResContextMenu == R.menu.contact_context) {
activity.contact_context_id = acmi.position;
final Contact contact = (Contact) activity.contacts.get(acmi.position);
final MenuItem blockUnblockItem = menu.findItem(R.id.context_contact_block_unblock);
final MenuItem showContactDetailsItem = menu.findItem(R.id.context_contact_details);
if (contact.isSelf()) {
showContactDetailsItem.setVisible(false);
}
XmppConnection xmpp = contact.getAccount().getXmppConnection();
if (xmpp != null && xmpp.getFeatures().blocking() && !contact.isSelf()) {
if (contact.isBlocked()) {
blockUnblockItem.setTitle(R.string.unblock_contact);
} else {
blockUnblockItem.setTitle(R.string.block_contact);
}
} else {
blockUnblockItem.setVisible(false);
}
}
}
What you should rather use is a toggle button.
It has two states (ON and OFF).
In ON state you can show the list and in OFF state you can hide the list.
To hide or to make list visible use:
list.setVisibility(View.INVISIBLE)
list.setVisibility(View.VISIBLE)
To handle ON and OFF state of Toggle button
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
//ON state
} else {
//OFF state
}
}
});
The listview(lv) is made up with SimpleCursorAdapter and it represents the three textviews which are fethed from the database.
I've added the notifyDataSetChanged() after delete operations as well, but its not working. I've even added the invalideViews().
I'd be grateful for your assistance.
package com.snm.anand.whoowsme;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class homepage extends Activity {
ListView lv;
MyDatabase mdb = new MyDatabase(this);
Cursor c;
SimpleCursorAdapter sca;
public void onCreate(final Bundle SavedInstances) {
super.onCreate(SavedInstances);
setContentView(R.layout.homepage);
lv = (ListView) findViewById(R.id.listViewMain);
mdb.open();
c = mdb.getemp();
String [] from = {"ename","enumber","eamnt"};
int [] to = {R.id.textView3,R.id.textView4,R.id.textView5};
sca = new SimpleCursorAdapter(getApplicationContext(), R.layout.item, c, from, to);
lv.setAdapter(sca);
sca.notifyDataSetChanged();
registerForContextMenu(lv);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Click to delete the entry.");
menu.add("Delete");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getTitle()=="Delete"){
Log.w("myapp", "dele");
int position = item.getItemId();
long pid = lv.getItemIdAtPosition(position);
mdb.empdelete(pid);
c = mdb.getemp();
lv.invalidateViews();
sca.notifyDataSetChanged();
}
return super.onContextItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml
switch (item.getItemId()) {
case R.id.addNewPerson:
startActivity(new Intent(this, addNewPerson.class));
default:
return super.onOptionsItemSelected(item);
}
}
}
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.
I have an application with a list view and a custom adapter where I add custom objects to the list view. I know how to delete objects through long-pressing one of the list items in the list, but I have a trash can action bar button and I want it so that when you click on that button, it brings up the same CAB as if you were long-pressing a list item, and I want the user to be able to select multiple list items, and then click a delete button on the CAB.
What I have tried:
package viva.inspection.com.inspectionpicker;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.SparseBooleanArray;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.List;
import viva.inspection.com.inspectionpicker.R;
public class ListActivity extends Activity {
private static ArrayList<InspectionItem> inspections;
private static final String s = "inspection list";
public static final String PREFS_NAME = "MyPrefsFile";
ListView inspectionList;
private final int GET_VALUE=111;
private final int GET_VAL = 11;
private MyAdapter listviewadapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
inspectionList = (ListView) findViewById(R.id.listView);
inspectionList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
inspections = new ArrayList<InspectionItem>();
inspections.add(new InspectionItem(new GregorianCalendar(7,15,14), "hi", "hi", "hi", "hi", "hi", "hi", "hi", "hi", "hi", "hi", new ArrayList<String>()));
if(getIntent().getStringExtra("NEW_VALUE") != null) {
//addItems(getIntent().getStringExtra("NEW_VALUE"));
SharedPreferences.Editor edit = settings.edit();
edit.putString("myKey", TextUtils.join(",", inspections));
edit.commit();
}
if(!(settings.getString("myKey", "hi").equals("hi"))) {
//We have saved values. Grab them.
} else {
//We have no saved values
inspections = new ArrayList<InspectionItem>();
inspections.add(new InspectionItem(new GregorianCalendar(7,15,14), "hi", "hi", "hi", "hi", "hi", "hi", "hi", "hi", "hi", "hi", new ArrayList<String>()));
}
listviewadapter = new MyAdapter(this, R.layout.row_layout,
inspections);
inspectionList.setAdapter(listviewadapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.list, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch(id) {
case R.id.action_settings:
return true;
case R.id.action_new:
Intent intent = new Intent(this, InitialChoose.class);
startActivity(intent);
return true;
case R.id.action_delete:
inspectionList.setOnItemSelectedListener(new ActionBarCallBack());
startActionMode(new ActionBarCallBack());
//mActionMode.finish();
return true;
}
return super.onOptionsItemSelected(item);
}
class ActionBarCallBack implements ListView.OnItemSelectedListener, ActionMode.Callback {
ActionMode activeMode;
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.delete:
// Calls getSelectedIds method from ListViewAdapter Class
SparseBooleanArray selected = listviewadapter
.getSelectedIds();
// Captures all selected ids with a loop
for (int i = (selected.size() - 1); i >= 0; i--) {
if (selected.valueAt(i)) {
InspectionItem selecteditem = listviewadapter
.getItem(selected.keyAt(i));
// Remove selected items following the ids
listviewadapter.remove(selecteditem);
}
}
// Close CAB
mode.finish();
return true;
default:
return false;
}
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.cab_menu, menu);
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
// TODO Auto-generated method stub
listviewadapter.removeSelection();
}
#Override
public boolean onPrepareActionMode(final ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
listviewadapter.toggleSelection(i);
final int checkedCount = inspectionList.getCheckedItemCount();
// Set the CAB title according to total checked items
activeMode.setTitle(checkedCount + " Selected");
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
/*
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==RESULT_OK){
if(requestCode == GET_VALUE){
if(data.getStringExtra("NEW_VALUE")!=null && data.getStringExtra("NEW_VALUE").length()>0){
addItems(data.getStringExtra("NEW_VALUE"));
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor edit = settings.edit();
edit.putString("myKey", TextUtils.join(",", inspections));
edit.commit();
}
}
}
} */
}
Basically, with this code, if I click on the trash-can action bar button, the CAB shows up, but I can't select any items on the list and proceed to delete them. Any help is greatly appreciated.
This is a tricky one. I used CheckedTextView's for multiple selections inside the list however when the list scrolls the adapter re-uses the old views and sometimes checks the wrong items. To overcome that I used an array of all the currently checked items, so the adapter can know which items should be checked.
Before going back to the original list you need to call notifyDataSetChanged(), which notifies to redrawn the visible views therefore uncheck/delete the selections (depends on what action you chose back at the CAB).
package com.example.simon.cabdelete;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Simon on 2014 Jul 18.
*/
public class MainActivity extends Activity {
private final static String TAG = "MainActivity";
MyAdapter mAdapter;
ListView mListView;
List<String> mListArray;
SparseBooleanArray mCheckedItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.listView);
// Default list item click listener
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Do something on normal click
}
});
mCheckedItems = new SparseBooleanArray();
int size = 20;
mListArray = new ArrayList<String>(size);
for (int i=0; i<size; i++)
mListArray.add("Item "+i);
mAdapter = new MyAdapter(this, R.layout.list_item, mListArray);
mListView.setAdapter(mAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch (id) {
case R.id.action_settings:
break;
case R.id.action_delete:
startActionMode(new ActionBarCallBack());
break;
}
return super.onOptionsItemSelected(item);
}
public class MyAdapter extends ArrayAdapter<String> {
List<String> items;
int itemResource;
LayoutInflater inflater;
public MyAdapter(Context ctx, int resource, List<String> objects) {
super(ctx, resource, objects);
this.items = objects;
this.itemResource = resource;
this.inflater = ((MainActivity)ctx).getLayoutInflater();
}
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
// (Re)Use convertView
if (convertView == null) {
convertView = inflater.inflate(itemResource, parent, false);
}
CheckedTextView checkView = (CheckedTextView) convertView;
checkView.setText(items.get(pos));
if (mCheckedItems.get(pos))
checkView.setChecked(true);
else
checkView.setChecked(false);
return convertView;
}
}
public class ActionBarCallBack implements ListView.OnItemClickListener,
ActionMode.Callback {
ActionMode actionMode;
AdapterView.OnItemClickListener previousListener;
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
Log.v(TAG, "Action mode started");
actionMode = mode;
mode.getMenuInflater().inflate(R.menu.cab_menu, menu);
previousListener = mListView.getOnItemClickListener();
mListView.setOnItemClickListener(this);
mCheckedItems = new SparseBooleanArray(mListView.getCount());
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.delete:
Log.v(TAG, "Deleting "+mCheckedItems.size()+" items");
for (int i= mCheckedItems.size()-1; i>=0; i--) {
int key = mCheckedItems.keyAt(i);
Log.v(TAG, "Removing array item # " + key);
mListArray.remove(key);
}
mode.finish();
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode mode) {
Log.v(TAG, "Exiting action mode.");
mListView.setOnItemClickListener(previousListener);
mCheckedItems.clear();
mAdapter.notifyDataSetChanged();
}
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
CheckedTextView checkView = (CheckedTextView) view;
boolean state = checkView.isChecked();
checkView.setChecked(!state);
if (!mCheckedItems.get(position))
mCheckedItems.put(position, true);
else
mCheckedItems.delete(position);
actionMode.setTitle(mCheckedItems.size() + " Items selected");
Log.v(TAG, "Action item # " + position +
" clicked. It's state now is " + state);
}
}
}
And here are my xml files create the whole look:
res/layout/activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="true"/>
<!-- Note that drawSelectorOnTop is important as it lets
the CheckedTextViews to be clicked in a normal way too-->
</RelativeLayout>
res/layout/list_item.xml:
<CheckedTextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:background="#drawable/list_selector"/>
res/drawable/list_selector.xml:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#color/item_default" android:state_checked="false"/>
<item android:drawable="#color/item_checked" android:state_checked="true"/>
</selector>
res/values/colors.xml:
<resources>
<color name="item_default">#33B5E5</color>
<color name="item_checked">#0095CC</color>
</resources>
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);