How to handle long tap on ListView item? - android

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;
}
});

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)

Longclick Issue

I have the following code, which runs when I click on my list, but I need it to only pop up a menu when I long click, the short click does other things.
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId()==R.id.listView1) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_list, menu);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch(item.getItemId()) {
case R.id.add:
// add stuff here
CreateWO.performClick();
return true;
case R.id.punchin:
final Country country = (Country) ListView1.getItemAtPosition(getwoindex());
punchin.performClick();
Toast.makeText(getApplicationContext(), "Work Order="+country.code, Toast.LENGTH_SHORT).show();
return true;
case R.id.punchout:
punchout.performClick();
return true;
default:
return super.onContextItemSelected(item);
}
}
For normal click on listView item use: listView.onItemClickListener and for long click use: listView.setOnItemLongClickListener as follows:
ListView lv =(ListView)findViewById(R.id.my_list);
----
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Do something
}
});
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//do something on long click
//like show contextMenu
return false;
}
});
EDIT:
For ContextMenu:
You can either call openContextMenu(view) in your onItemLongClick (as above) OR you can use registerForContextMenu(view), for example:
lv.setAdapter(adapter);
registerForContextMenu(lv);
By default contextMenu will open when a user long clicks your view. In this case you do not need to call onLongClick manually on the listView.

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

context menu for List view inside dialog box 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 :)

Long click on ListFragment

I'm working with a ListFragment and doing a onListItemClick. Everything works fine, but now I want to use a long Item Click (e.g setOnItemLongClickListener(new OnItemLongClickListener() for an Activity). How can I use this in my fragment?
Thanks!
Yes, the solution posted by tsync works for me. I too had ran into same problem and considered that this is not possible. I tried the above suggestion as follows:
public class ProjectsFragment extends ListFragment {
#Override
public void onActivityCreated(Bundle savedState) {
super.onActivityCreated(savedState);
getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
Toast.makeText(getActivity(), "On long click listener", Toast.LENGTH_LONG).show();
return true;
}
});
and it worked!
Depending on what you want to realize you can use the given methods for context menues:
First register the View class which gets long pressed (inside your Fragment class):
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
registerForContextMenu(this.getListView());
}
Than implement these two methods, to create a context menu and do what ever you want when a menu item is clicked:
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = this.getActivity().getMenuInflater();
inflater.inflate(R.menu.my_context_menu, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.add: // <-- your custom menu item id here
// do something here
return true;
default:
return super.onContextItemSelected(item);
}
}
This works for me
getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> av, View v, int position, long id) {
//Get your item here with the position
return true;
}
});

Categories

Resources