Android custom list dialog

user577732 picture user577732 · Mar 9, 2011 · Viewed 21.5k times · Source

Hi,
I'm working on a simple file browser app. I have most of it set up (where it lists everything out in the different directories and what not) but what I'm stuck on right now (worked on it for a few hours) is when a list item is selected, I want to have a custom list dialog appear. I found this code on the android development page and modded it slightly. Currently it just gives a toast of what was selected but I need the three items to be separate. That is, I'd like to do more than a toast and have each selection run different commands. Here is my current code

    final CharSequence[] items = {"Info", "Rename", "Delete"};

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Options for " + file.getName());
    builder.setItems(items, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) {
            Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
        }
    }).show();

Thanks to anyone who can help me just separate it. I've tried a few different variations of if statements and what not but everything I've tried has failed.

Answer

Durza007 picture Durza007 · Mar 9, 2011

The item integer you receive is the index of the charsequence array that contains your actions, so to get the action that was selected you could do like this (inside your onClick method):

if (item == 0)
{
     // Info item
}
else if (item == 1)
{
     // Rename, and so one

Or you could do like this:

if (items[item].equals("Info"))
{
     // Info item
}
else if (items[item].equals("Rename")
{
     // Rename, and so one
}

But the first method is prefered