Nicolas Mustaro
Nicolas Mustaro

Reputation: 681

Dynamically creating a floating context menu with listener for each item?

I've seen a few questions asking this for VB and C#, but nothing for Java/Android. Basically I have an ArrayList of values, all numbers, and I want to provide the user an option for removing a specific entry. What I want to do is when the user clicks a "Remove Entry" button, a floating context menu appears populated with options of the ArrayList entries, in order of which they appear in the list. When they click a number in the menu, it is removed from the ArrayList.

I'm fairly new to menu creation, but I've created them via xml many times. This is the first time I'm attempting to create a floating menu dynamically with an undetermined number of items.

Upvotes: 0

Views: 488

Answers (1)

tmh
tmh

Reputation: 1445

If the list of numbers is reasonably short from the UX point of view (i.e. users don't want to search/filter the list), you can use a traditional single-choice list AlertDialog. You just need to modify the example from the docs slightly:

final List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);

final CharSequence[] numbers = new CharSequence[list.size()];
for (int i = 0; i < list.size(); i++) {
    numbers[i] = list.get(i).toString();
}

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Remove entry:");
builder.setItems(numbers, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        list.remove(which);
    }
});
builder.create().show();

As you can see in the docs, the setItems method is overloaded to accept a CharSequence array. So basically, you need to convert the numbers to CharSequences before creating the Dialog. (String implements CharSequence, thus toString() does the job.)

In the OnClickListener, the index of the selected menu item is passed as which to the onClick method. As the menu item index and the list item index are the same, you can use which to remove the item from the actual list.

The same approach works for lists of floats, just format them according to locale.

Upvotes: 1

Related Questions