Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create an expandable list AlertDialog?

In my app the users are able to select articles to download using different criteria. One of them is year and month. For this I would like an AlertDialog with a list of years. If the user then clicks on a year, the list will expand and show january, february etc.

I know how to make an expandable listview using a SimpleExpandableListAdapter but that is not what I want. Since the other criteria (eg. category) are also list AlertDialogs, I want something that is similar in look and feel.

Is it possible to accomplish such an expandable list AlertDialog?

SOLUTION

This is what I ended up with based on CommonsWare's solution:

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select something");

ExpandableListView myList = new ExpandableListView(this);
MyExpandableListAdapter myAdapter = new MyExpandableListAdapter();
myList.setAdapter(myAdapter);

builder.setView(myList);
AlertDialog dialog = builder.create();
dialog.show();

Only problem remaining: how do I implement the onClick listener for the AlertDialog? Normally I would do it in the setItems() method, but am not using setItems.

I added myList.setOnItemClickListener after myList.setAdapter() but it is ignored. Nothing happens when I click an item:

myList.setOnItemClickListener(new ListView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> a, View v, int i, long l) {
        try {
            Toast.makeText(ExpandableList1.this, "You clicked me", Toast.LENGTH_LONG).show();
        }
        catch(Exception e) {
            System.out.println("something wrong here    ");
        }
    }
});

Solution to click problem:

The solution was quite simple. Since it is an expandable list, item clicks are captured by the list itself to open the child elements. Thus, the event handler is never called.

Instead you have to implement OnChildClickListener() that - as the name suggests - listens to child clicks!

like image 974
marlar Avatar asked Jul 10 '11 20:07

marlar


2 Answers

Use setView() on AlertDialog.Builder, passing in an ExpandableListView that you inflate or create in Java code and have set your adapter on.

like image 144
CommonsWare Avatar answered Nov 13 '22 11:11

CommonsWare


Well, to use the listviews you have to extend the appropriate list-activity, in your case ExpandableListActivity. You wont be able to find a ExpandableListDialog to extend.

I suppose you might be able to implement it in the activity which calls the dialog, and pass on the listview to the dialog as a reference, and manually add it to your layout in the dialog. Im not sure if this will work, but its worth a shot :D

like image 38
JustDanyul Avatar answered Nov 13 '22 11:11

JustDanyul