Question

I have an GUI interface with the method public Item selectItem(Item[] items); which returns one of the items; I implemented this interface into my Activity and used an AlertDialog which lets the user select one Item. Here is my code:

private Item tempItem;

@Override
    public Item selectItem(final Item[] items) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Select an Item");
        builder.setItems(toStringArray(items), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int choice) {
                tempItem = items[choice];
            }

        });
        builder.setCancelable(false);
        builder.show();
        return tempItem;
    }

tempItem is a support variable becuase I can't return the value inside the onClick() method. The problem is that the method returns null because tempItem is not jet set. Is there a better solution to implement this method using AlertDialog?

Était-ce utile?

La solution

I would implement a click listener for your class that allows you to use onClick as a class method and thus work with it's variables.

public class YourClass extends Whatever implements DialogInterface.OnClickListener{
    private item;
    private Item[] items;
    private AlertDialog.Builder builder1;
    private AlertDialog.Builder builder2;

    @Override
    public Item selectItem(final Item[] items) {
        this.items = items;
        AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
        builder1.setTitle("Select an Item");
        builder1.setItems(toStringArray(items), new DialogInterface.OnClickListener(this));
        builder1.setCancelable(false);
        builder1.show();

        return item;
    }

    @Override
    protected void onClick(DialogInterface dialog, int choice){
        if(dialog.equals(builder1)
            item = items[choice];
        else if(dialog.equals(builder2))
            // do what you want for dialog 2
    }
}

Just an option, but it is how I have done it when I have had to do similar things in the past.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top