Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are clicks in my ExpandableListView ignored?

I have an AlertDialog populated by an ExpandableListView. The list itself works perfectly, but for some reason clicks are ignored. Apparently my click handler is never called.

This is the code:

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select something");
ExpandableListView myList = new ExpandableListView(this);
MyExpandableListAdapter myAdapter = new MyExpandableListAdapter();
myList.setAdapter(myAdapter);
myList.setOnItemClickListener(new ExpandableListView.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    ");
        }
    }
});
builder.setView(myList);
dialog = builder.create();
dialog.show();

If I instead try to populate the AlertDialog with a plain listview, click events are generated without problems:

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

ListView modeList = new ListView(this);
String[] stringArray = new String[] { "Bright Mode", "Normal Mode" };
ArrayAdapter<String> modeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, stringArray);
modeList.setAdapter(modeAdapter);
modeList.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {
          // When clicked, show a toast with the TextView text
          Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
              Toast.LENGTH_SHORT).show();
        }
      });


builder.setView(modeList);
AlertDialog dialog1 = builder.create();
dialog1.show();

What could be the reason why click event fails in my ExpandableListView but not in a normal ListView? I am probably missing something, but I have no idea what that could be.

like image 719
marlar Avatar asked Jul 14 '11 13:07

marlar


1 Answers

Ok, 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 154
marlar Avatar answered Oct 16 '22 04:10

marlar