Search code examples
androidobjectonclickonclicklistenerexpandablelistview

How to pass whole object to intent in onChildClick in ExpandableListView


In GridView or simple ListView, I'm using this code to pass an object to a new activity and it works just fine:

gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Illusion i = (Illusion) parent.getItemAtPosition(position);
            Intent intent = new Intent(IllusionsGridActivity.this, ViewIllusionActivity.class);
            intent.putExtra("item", i);
            startActivity(intent);
        }
    });

I'm trying to do the same in Expandable list to child objects, but it doesn't work. It seems to accept only String values. So this doesn't work:

listView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
        @Override
        public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
            Illusion i = (Illusion) parent.getItemAtPosition(childPosition);
            Intent intent = new Intent(IllusionsListActivity.this, ViewIllusionActivity.class);
            intent.putExtra("item", i);
            startActivity(intent);
            return false;
        }
    });

Is there a way how to pass whole object to a new activity inside this method?


Solution

  • Try next code:

    listView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
        @Override
        public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
            long packedPosition = ExpandableListView.getPackedPositionForChild(groupPosition, childPosition);
            int flatPosition = parent.getFlatListPosition(packedPosition)
            Illusion i = (Illusion) parent.getItemAtPosition(flatPosition);
            Intent intent = new Intent(IllusionsListActivity.this, ViewIllusionActivity.class);
            intent.putExtra("item", i);
            startActivity(intent);
            return false;
        }
    });