Search code examples
androiddialogonclickandroid-alertdialogonlongclicklistener

Display AlertDialog onLongClick


I have a listView and a onClickListener that onClick do som things and it works. Now I want to display an AlertDialog onLongClick but nothing happens. I've added android:longClickable="true" to the ListView in the manifest too but still, nothing happens.

listView.setOnLongClickListener(new OnLongClickListener() {

    public boolean onLongClick(View v) {

        final CharSequence[] items = {"Revansch!", "Lägg till som vän","Ta bort spelet"};

        AlertDialog.Builder builder = new AlertDialog.Builder(ChallengeList.this);

        builder.setItems(items, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
            }
        });
        AlertDialog alert = builder.create();
        alert.show();
        return true;

    }

});

Anyone know why it's not working? Thanks in advance!


Solution

  • Try this,

    listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> av, View v, int pos, final long id) {
    
           final CharSequence[] items = {"Revansch!", "Lägg till som vän","Ta bort spelet"};
           AlertDialog.Builder builder = new AlertDialog.Builder(ChallengeList.this);
           builder.setItems(items, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int item) {
                    Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
                }
            });
            AlertDialog alert = builder.create();
            alert.show();
    
            return true;
        }
    });