context menu for List view inside dialog box android - android

I have custom dialog box which contains a list view. I want a context menu to appear when i long press the list item within the dialog. The context menu appears but nothing happens when i click any of it's items. I've provided the actions to perform when a context menu item is clicked but nothing happens. Can anyone pls help?
final ArrayList<ListClass> listItem = coreData_.listItem_;
LayoutInflater inflater = (LayoutInflater)
GUI.this.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.scanlist,
(ViewGroup) findViewById(R.id.scan_dialog));
AlertDialog.Builder builder =
new AlertDialog.Builder(GUI.this);
builder.setView(layout);
scanListView_ = (ListView)
layout.findViewById(R.id.scan_list_view);
registerForContextMenu(scanListView_);
scanListView_.setOnCreateContextMenuListener(this);
scanListView_.setBackgroundColor(Color.rgb(0, 0, 0));
scanListView_.setAdapter(
new EfficientAdapter(getApplicationContext(),
listItem));
scanListView_.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
//perform list item click actions
}
});
builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//dismiss
}
});
availNetDialog_ = builder.create();
availNetDialog_.setTitle("Available Networks");
availNetDialog_.show();

public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
// second argument show what item was selected
menu.add(0, 0, 1, "Delet Row").setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == 0) {
// get item id from listView if needed
AdapterView.AdapterContextMenuInfo acmi = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
// extract id and transfer it to another method delRec
delRec(acmi.id);
//init();
return true;
}
return false;
}
});
}
In summary just setOnMenuItemClickListener and #Override onMenuItemClick.
Hope it help :)

Related

remove item onlongclick from listview

I want when long pressing an item of my list to give an option delete and delete the item if it pressed.
//onCreate()
alreadyAddedFood = (ListView) findViewById(R.id.alreadyAddedList);
registerForContextMenu(alreadyAddedFood);
//END of onCreate()
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_general, menu);
menu.setHeaderTitle("Select The Action");
}
#Override
public boolean onContextItemSelected(MenuItem item){
if(item.getItemId()==R.id.delete){
//How to delete?
Toast.makeText(getApplicationContext(),"delete"+item,Toast.LENGTH_LONG).show();
}else{
return false;
}
return true;
}
UPDATE
I also have this class which i implement the onlongClickListener and it works fine but without giving the user the option to press delete like the photo below
public void alreadyAdded(String searchedMessage) {
itemsAdded.add(searchedMessage);
final ArrayAdapter<String>addedAdapter= new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,itemsAdded);
alreadyAddedFood.setAdapter(addedAdapter);
alreadyAddedFood.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
// #Override
// public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
// itemsAdded.remove(position);
// addedAdapter.notifyDataSetChanged();
// Toast.makeText(AddFood.this, "Item Deleted", Toast.LENGTH_LONG).show();
// return true;
// }
// });
}
Add this in your onContextItemSelected :
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); // init the info to get the position from
items.remove(info.position); // remove the item from the list
adapter.notifyDataSetChanged(); //updating the adapter
You can do Something like this:
private ListView ls;
ls.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int arg2, long arg3) {
ls.remove(arg2);//where arg2 is position of item you click
myAdapter.notifyDataSetChanged();
return false;
}
});
You can pop up a dialog and ask the user for his confirmation.
However, it is less aesthetic. I would recommend one of these:
After the long click, show a delete option (using the delete icon rather than text) in the app-bar.
Do not support long click, instead use an swipe-able rows with a delete option (again, with an icon) in the right/left of each row. (I will recommend this library.
(gif was taken from here)

How to set onContextItemClickListener for a context menu of ListView?

I have used the following code to set context menu for my listview. Now I want to create the onContextItemClickListener for that context menu. Apparently there no such method like listview.setOnContextItemClickListener. Kindly Help me out here.
ListView listView = new ListView(getApplicationContext());
#SuppressWarnings("unchecked")
ArrayAdapter listViewArrayAdapter = new ArrayAdapter(getApplicationContext(),
android.R.layout.simple_list_item_1, locations);
listView.setAdapter(listViewArrayAdapter);
listView.setFocusableInTouchMode(true);
listView.setOnFocusChangeListener(
new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View arg0, boolean arg1) {
Log.i("SampleApp", "onFocusChanged() - view=" + arg0);
}
});
listView.setOnItemClickListener( new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView adapterView, View view,
int arg2, long arg3) {
int selectedPosition = adapterView.getSelectedItemPosition();
Log.i("SampleApp", "Click on position"+selectedPosition);
}
});
listView.setOnCreateContextMenuListener(
new View.OnCreateContextMenuListener() {
public void onCreateContextMenu(ContextMenu menu, View view,
ContextMenu.ContextMenuInfo menuInfo) {
AdapterContextMenuInfo mi = (AdapterContextMenuInfo) menuInfo;
menu.add(0, 0, 0, "Delete");
}
});
You should add:
// we register for the contextmneu
registerForContextMenu(lv);
to register for context menu (i.e lv is the instance of ListView) and then:
// This method is called when user selects an Item in the Context menu
#Override
public boolean onContextItemSelected(MenuItem item) {
int itemId = item.getItemId();
// do your logic here
return true;
}
Hope this is what you are looking for.
PS: If you are interested i wrote a post about it, give a look here

Android ListView can't click Item

I have a ListView. I implemented OnItemClickListener to open a ContextMenu when an item is clicked.
lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
showMenu(view);
}
});
And the code to create menu.
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.layout.friend_list_menu, menu);
}
public void showMenu(View v) {
registerForContextMenu(v);
openContextMenu(v);
}
My problem is, when I clicked on one item of ListView, it does open the Menu. But if I go back to the ListView, I can't click that item again. The same for other items, it can't be click after close the menu. Can anyone help me with this?
You've set that up incorrectly. You register for context menu when you set the adapter, not in a button click.
It should look like this:
setListAdapter(lists);
registerForContextMenu(getListView());
Then you have your onCreateContextMenu and onContextItemSelected methods (I create mine programatically, but your inflated one woudl work just as well):
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("List Operations");
menu.add(0, v.getId(), 0, "Edit List");
menu.add(0, v.getId(), 0, "Delete List");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
if (item.getTitle() == "Edit List") {
// Do your edit stuff here
} else if (item.getTitle() == "Delete List") {
// Do your delete stuff here
}
return super.onContextItemSelected(item);
}
You don't need to use onItemClick unless you want to do something on a short press of the item (context menu is long press).
The following code will works.
code:
ListView listview=(ListView)findViewByid(R.id.listview);
/**** here write appending data to listview*******/
ArrayAdapter<String> adp=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,/**your list items**/);
listview.setadapter(adp);
registerForContextMenu(listview);
//listview item click listener
listview.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View v, int p, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "selected" + p, 30).show();
}});
/****do your context menu code here*******/

How to handle long tap on ListView item?

How can I catch such event? onCreateContextMenu is quite similiar, but I don't need menu.
It's hard to know what you need to achieve. But my guess is that you want to perform some acion over the item that receives the long click. For that, you have two options:
add an AdapterView.OnItemLongClickListener. See setOnItemLongClickListener.
.
listView.setOnItemLongClickListener (new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView parent, View view, int position, long id) {
//do your stuff here
}
});
if you are creating a custom adapter, add a View.OnLongClickListener when creating the View in the method Adapter#getView(...)
Normally, you'd associate a long click on a list view with a context menu, which you can do by registering the listView with Activity.registerForContextMenu(View view) to give a more consistent user interface experience with other android apps.
and then override the onContextItemSelected method in your app like this:
#Override
public void onCreate(Bundle savedInstanceState) {
listView = (ListView) findViewById(R.id.your_list_view);
registerForContextMenu(listView);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle(getString(R.string.menu_context_title));
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.your_context_menu, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.some_item:
// do something useful
return true;
default:
return super.onContextItemSelected(item);
}
The position in the list is also held in info.id
If you just want to capture the long click event, then I think what Snicolas is suggesting would work.
Add a custom View.OnLongClickListener to your views. It can be shared by many instances, then you can use the parameter of
onLongClick(View v)
to know which view has been clicked and react accordingly.
Regards,
Stéphane
//Deleted individual cart items
//on list view cell long press
cartItemList.setOnItemLongClickListener (new OnItemLongClickListener() {
#SuppressWarnings("rawtypes")
public boolean onItemLongClick(AdapterView parent, View view, final int position, long id) {
final CharSequence[] items = { "Delete" };
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Action:");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
cart = cartList.get(position);
db.removeProductFromCart(context, cart);
new AlertDialog.Builder(context)
.setTitle(getString(R.string.success))
.setMessage(getString(R.string.item_removed))
.setPositiveButton("Done", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(CartDetailsActivity.this, HomeScreen.class);
startActivity(intent);
}
})
.show();
}
});
AlertDialog alert = builder.create();
alert.show();
//do your stuff here
return false;
}
});

Detecting which selected item (in a ListView) spawned the ContextMenu (Android)

I have a ListView that will allow the user to long-press an item to get a context menu. The problem I'm having is in determining which ListItem they long-pressed. I've tried doing this:
myListView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
#Override public void onCreateContextMenu(ContextMenu menu, final View v, ContextMenuInfo menuInfo) {
menu.add("Make Toast")
.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override public boolean onMenuItemClick(MenuItem item) {
String toastText = "You clicked position " + ((ListView)v).getSelectedItemPosition();
Toast.makeText(DisplayScheduleActivity.this, toastText, Toast.LENGTH_SHORT).show();
return true;
}
});
}
});
but it just hangs until an ANR pops up. I suspect that after the menu is created the ListItem is no longer selected.
It looks like you could monitor for clicks or long-clicks then record the clicked item there:
mArrivalsList.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
// record position/id/whatever here
return false;
}
});
but that feels majorly kludgey to me. Does anyone have any better solutions for this?
I do exactly this. In my onCreateContextMenu(...) method, I cast the ContextMenu.ContextMenuInfo to AdapterView.AdapterContextMenuInfo. From there, you can get the targetView, which you cast again to the widget. The complete code is available in HomeActivity.java, look for the onCreateContextMenu(...) method.
#Override
public void onCreateContextMenu(ContextMenu contextMenu,
View v,
ContextMenu.ContextMenuInfo menuInfo) {
AdapterView.AdapterContextMenuInfo info =
(AdapterView.AdapterContextMenuInfo) menuInfo;
selectedWord = ((TextView) info.targetView).getText().toString();
selectedWordId = info.id;
contextMenu.setHeaderTitle(selectedWord);
contextMenu.add(0, CONTEXT_MENU_EDIT_ITEM, 0, R.string.edit);
contextMenu.add(0, CONTEXT_MENU_DELETE_ITEM, 1, R.string.delete);
}
Note that I store the selected text as well as the select id in private fields. Since the UI is thread confined, I know the selectedWord and selectedWordId fields will be correct for later actions.
First of all, I'm wondering if you're making things a little overly complicated by using View.setOnCreateContextMenuListener(). Things get a lot easier if you use Activity.registerForContextMenu(), because then you can just use Activity.onCreateContextMenu() and Activity.onContextItemSelected() to handle all of your menu events. It basically means you don't have to define all these anonymous inner classes to handle every event; you just need to override a few Activity methods to handle these context menu events.
Second, there's definitely easier ways to retrieve the currently selected item. All you need to do is keep a reference either to the ListView or to the Adapter used to populate it. You can use the ContextMenuInfo as an AdapterContextMenuInfo to get the position of the item; and then you can either use ListView.getItemAtPosition() or Adapter.getItem() to retrieve the Object specifically linked to what was clicked. For example, supposing I'm using Activity.onCreateContextMenu(), I could do this:
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
// Get the info on which item was selected
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
// Get the Adapter behind your ListView (this assumes you're using
// a ListActivity; if you're not, you'll have to store the Adapter yourself
// in some way that can be accessed here.)
Adapter adapter = getListAdapter();
// Retrieve the item that was clicked on
Object item = adapter.getItem(info.position);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
// Here's how you can get the correct item in onContextItemSelected()
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
Object item = getListAdapter().getItem(info.position);
}
this is another way on how to create context menu n how to delete the item selected here is the whole code
public class SimpleJokeList extends Activity {
public static final int Upload = Menu.FIRST + 1;
public static final int Delete = Menu.FIRST + 2;
int position;
ListView lv;
EditText jokeBox;
Button addJoke;
MyAdapter adapter;
private ArrayAdapter<String> mAdapter;
private ArrayList<String> mStrings = new ArrayList<String>();
String jokesToBeAdded;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simplejokeui);
lv=(ListView)findViewById(R.id.jokelist);
addJoke=(Button)findViewById(R.id.addjoke);
jokeBox=(EditText)findViewById(R.id.jokebox);
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mStrings);
registerForContextMenu(lv);
listItemClicked();
addJokes();
private void addJokes() {
// TODO Auto-generated method stub
addJoke.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
jokesToBeAdded=jokeBox.getText().toString();
if(jokesToBeAdded.equals("")){
Toast.makeText(getApplicationContext(), "please enter some joke", Toast.LENGTH_LONG).show();
}
else{
lv.setAdapter(mAdapter);
mAdapter.add(jokesToBeAdded);
jokeBox.setText(null);
}
}
});
}
private void listItemClicked() {
// TODO Auto-generated method stub
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
position=arg2;
return false;
}
});
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
populateMenu(menu);
menu.setHeaderTitle("Select what you wanna do");
}
private void populateMenu(ContextMenu menu) {
// TODO Auto-generated method stub
menu.add(Menu.NONE, Upload, Menu.NONE, "UPLOAD");
menu.add(Menu.NONE, Delete, Menu.NONE, "DELETE");
}
#Override
public boolean onContextItemSelected(MenuItem item)
{
return (applyMenuChoice(item) || super.onContextItemSelected(item));
}
private boolean applyMenuChoice(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId())
{
case Delete:
String s=mAdapter.getItem(position);
mAdapter.remove(s);
// position--;
Toast.makeText(getApplicationContext(),"Congrats u HAve Deleted IT", Toast.LENGTH_LONG).show();
return (true);
}
return false;
}
And don't forget to put this
registerForContextMenu(listview);
in your onCreate method to get your context Menu visible.
We have used with success:
#Override
public boolean onContextItemSelected
(
MenuItem item
)
{
if (!AdapterView.AdapterContextMenuInfo.class.isInstance (item.getMenuInfo ()))
return false;
AdapterView.AdapterContextMenuInfo cmi =
(AdapterView.AdapterContextMenuInfo) item.getMenuInfo ();
Object o = getListView ().getItemAtPosition (cmi.position);
return true;
}
Isn't the view argument the actual selected row's view, or am I missing the question here?
ListView lv;
private OnItemLongClickListener onLongClick = new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
lv.showContextMenuForChild(arg1);
lv.showContextMenu();
return false;
}
};
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
View TargetV=(View) info.targetView;
text1 = (String) ((TextView) TargetV.findViewById(R.id.textView1)).getText();
text2 = (String) ((TextView) TargetV.findViewById(R.id.textView2)).getText();
if(List3Ok){
text3 = (String) ((TextView) TargetV.findViewById(R.id.textView3)).getText();
}
selectedWord = text1 + "\n" + text2 + "\n" + text3;
selectedWordId = info.id;
menu.setHeaderTitle(selectedWord);
MenuInflater inflater = this.getActivity().getMenuInflater();
inflater.inflate(R.menu.list_menu, menu);
}
I case you are using SimpleCursorAdapder you may do it like this
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
getActivity().getMenuInflater().inflate(R.menu.project_list_item_context, menu);
// Getting long-pressed item position
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
int position = info.position;
// Get all records from adapter
Cursor c = ((SimpleCursorAdapter)getListAdapter()).getCursor();
// Go to required position
c.moveToPosition(position);
// Read database fields values associated with our long-pressed item
Log.d(TAG, "Long-pressed-item with position: " + c.getPosition());
Log.d(TAG, "Long-pressed-item _id: " + c.getString(0));
Log.d(TAG, "Long-pressed-item Name: " + c.getString(1));
Log.d(TAG, "Long-pressed-item Date: " + c.getString(2));
Log.d(TAG, "Long-pressed-item Path: " + c.getString(3));
// Do whatever you need here with received values
}

Categories

Resources