Is it possible to create an expandable list AlertD

2019-03-24 18:26发布

问题:

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!

回答1:

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



回答2:

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



回答3:

you can even make android:theme="Theme.Dialog" in the Manifest file on that particular Activity.