Search code examples
androidandroid-alertdialogonitemclicklisteneronlongclicklistener

Alertdialog multiple listeners


I created a Dialog which displays a list of items.

Now I need to also catch long-click events for editing purposes.

How could this be archieved?

AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(R.string.select_a_person);
    final UserAdapter adapter = new UserAdapter(this);
    builder.setAdapter(adapter, new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            selecteduUser = (User) adapter.getItem(which);
            if (selecteduUser != null) {
                mName.setText(selecteduUser.getName());
            }
        } 
    });
    builder.create().show();

Solution

  • currently I am seeing two solution

    Option 1:

    create your own custom dialog. create a activity with list view ( or listactivity whatever you prefer) and set it's theme as dialog.

    android:theme="@android:style/Theme.Dialog"
    

    There you can easily handle list item click. Then while starting this custom dialog activity pass the list data you want to show.

    Option 2:

    set setOnShowListener in your alertdialog in your approach. let me edit from your last line of code

    AlertDialog dialog = builder.create();
    
    dialog.setOnShowListener(new OnShowListener() 
    {       
        @Override
        public void onShow(DialogInterface dialog) 
        {       
            ListView list = ad.getListView();
            list.setOnItemLongClickListener(new OnItemLongClickListener() 
            {
                @Override
                public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) 
                {
                    // DO your task
                    return true;
                }           
            });     
        }
    });
    dialog.show();