Search code examples
androidonitemclicklisteneronitemlongclicklistener

How to override OnItemClickListener with OnItemLongClickListener


I have OnItemClickListener in my activity for list view in which i start another activity,and i also have OnItemLongClickListener in which basically i want to delete the long clicked row.When i click on list view OnItemClickListener works fine,but when when i long click on list still both OnItemClickListener and OnItemLongClickListener.And i don't want OnItemClickListener to work when i click long. This is how my code looks like.

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Intent intent = new Intent(MainActivity.this, CompleteInformationActivity.class);
                    intent.putExtra("position", "" + selected.get(position));
                    startActivity(intent);
                }
            });
            listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                    Toast.makeText(MainActivity.this, "Long click happened.", Toast.LENGTH_SHORT).show();
                    adapter.notifyDataSetChanged();
                    final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle("Do you want to delete?");
                    builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                                                            Toast.makeText(MainActivity.this, "Item is Deleted.", Toast.LENGTH_SHORT).show();

                        }
                    });
                    builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "Item is not Deleted.", Toast.LENGTH_SHORT).show();

                        }
                    });

                    AlertDialog dialog = builder.create();
                    dialog.show();
                    return false;
                }
            });

Solution

  • I think you should return true in your onItemLongClick method to consume the click. Check Android documentation http://developer.android.com/reference/android/widget/AdapterView.OnItemLongClickListener.html