Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4558086
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 21, 20262026-05-21T17:35:58+00:00 2026-05-21T17:35:58+00:00

I’ve got this java code and I’ve two questions: I would like to set

  • 0

I’ve got this java code and I’ve two questions:

  1. I would like to set a different icon for every child of every parent, but with this code I can only set the same icon for all child or an icon for a child situated in a X place and another icon for the other child.

  2. What did I do to start an activity when I press, for example, on the item called “Apple”?

How can I solve my problem? Thank you very much.

public class sedactivity extends ExpandableListActivity { 
    ExpandableListAdapter mAdapter;
    private final static String NAME = "NAME";
    private final static String SURNAME = "SURNAME";
    private Resources res;
    private Drawable photo, photo2, photo3, photo4;
    private List<Drawable> albumCovers;


    @Override
    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.list_main);

            // Create a List of Drawables to insert into the Expandable List
            // This can be completely dynamic
            res = this.getResources();
            photo = (Drawable) res.getDrawable(R.drawable.bee);
            photo2 = (Drawable) res.getDrawable(R.drawable.astro);
            photo3 = (Drawable) res.getDrawable(R.drawable.bomb);
            photo4 = (Drawable) res.getDrawable(R.drawable.apple);
            albumCovers = new ArrayList<Drawable>();
            albumCovers.add(photo);
            albumCovers.add(photo2);

            // The following code simply generates the Expandable Lists content (Strings)
            List<Map<String, String>> groupData = new ArrayList<Map<String, String>>();
            List<List<Map<String, String>>> childData = new ArrayList<List<Map<String, String>>>();
            Map<String, String>


            //List A
            curGroupMap = new HashMap<String, String>();
            groupData.add(curGroupMap);

            curGroupMap.put(NAME, "A");
            curGroupMap.put(SURNAME, "(2 Photos)");



            List<Map<String, String>> children = new ArrayList<Map<String, String>>();
            Map<String, String> curChildMap = new HashMap<String, String>();
            children.add(curChildMap);


            curChildMap.put(NAME, "Apple");


            curChildMap = new HashMap<String, String>();
            children.add(curChildMap);

            curChildMap.put(NAME, "Astro");

            curChildMap = new HashMap<String, String>();
            children.add(curChildMap);


            childData.add(children);


            //List B
            curGroupMap = new HashMap<String, String>();
            groupData.add(curGroupMap);


            curGroupMap.put(NAME, "B");
            curGroupMap.put(SURNAME, "(2 Photos)");

            children = new ArrayList<Map<String, String>>();

            curChildMap = new HashMap<String, String>();
            children.add(curChildMap);

            curChildMap.put(NAME, "Bee");

            curChildMap = new HashMap<String, String>();
            children.add(curChildMap);

            curChildMap.put(NAME, "Bomb");

            curChildMap = new HashMap<String, String>();
            children.add(curChildMap);


            childData.add(children);


            //List C
            curGroupMap = new HashMap<String, String>();
            groupData.add(curGroupMap);


            curGroupMap.put(NAME, "C");
            curGroupMap.put(SURNAME, "(0 Photo)");

            children = new ArrayList<Map<String, String>>();


            childData.add(children);

            // Set up our adapter
            mAdapter = new MyExpandableListAdapter(
                            this,
                            groupData,
                            R.layout.list_parent,
                            new String[] { NAME, SURNAME },
                            new int[] { R.id.rowText1, R.id.rowText2,R.id.photoAlbumImg },
                            childData,
                            R.layout.list_child,
                            new String[] { NAME, SURNAME },
                            new int[] { R.id.rowText1, R.id.photoAlbumImg }
                    );
            setListAdapter(mAdapter);
            registerForContextMenu(getExpandableListView());
    }


    /**
     * A simple adapter which allows you to bind data to specific
     * Views defined within the layout of an Expandable Lists children
     * (Implement getGroupView() to define the layout of parents)
     */


    public class MyExpandableListAdapter extends SimpleExpandableListAdapter {

            private List<? extends List<? extends Map<String, ?>>> mChildData;
            private String[] mChildFrom;
            private int[] mChildTo;

            public MyExpandableListAdapter(Context context,
                            List<? extends Map<String, ?>> groupData, int groupLayout,
                            String[] groupFrom, int[] groupTo,
                            List<? extends List<? extends Map<String, ?>>> childData,
                            int childLayout, String[] childFrom, int[] childTo) {
                    super(context, groupData, groupLayout, groupFrom, groupTo,
                          childData, childLayout, childFrom, childTo);

                    mChildData = childData;
                    mChildFrom = childFrom;
                    mChildTo = childTo;

            }

            public View getChildView(int groupPosition, int childPosition,
                    boolean isLastChild, View convertView, ViewGroup parent) {

            View v;
            if (convertView == null) {
                    v = newChildView(isLastChild, parent);
            } else {
                    v = convertView;
            }
            bindView(v, mChildData.get(groupPosition).get(childPosition), mChildFrom,
                            mChildTo, groupPosition, childPosition);
            return v;

            }

         // This method binds my data to the Views specified in the child xml layout
            private void bindView(View view, Map<String, ?> data, String[] from, int[] to, int groupPosition, int childPosition) {
                    int len = to.length - 1;
                    // Apply TextViews
                    for (int i = 0; i < len; ++i) {
                            TextView v = (TextView) view.findViewById(to[i]);
                            if (v != null) {
                                    v.setText((String) data.get(from[i]));
                            }
                            // Apply ImageView
                            ImageView imgV = (ImageView) view.findViewById(to[1]);
                            if (imgV != null) {
                                if(childPosition % 1 == 0) imgV.setImageDrawable(albumCovers.get(0));
                                else imgV.setImageDrawable(albumCovers.get(1));
                        }


                    }

            }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-21T17:35:59+00:00Added an answer on May 21, 2026 at 5:35 pm

    The line

    imgV.setImageDrawable(albumCovers.get(1))
    

    in your bindView method sets the image for the child view. You can set it to whatever you want, can make it data specific (say you have an image url in the data represented by this view, you can set the imgV to display that image.

    To attach a View.OnClickListener to every child item, you simply set it either in the overridden getChildView (for v/convertView) or your bindView method (for view):

    view.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            // TODO: Implement the tasks to be done here 
        }
    });
    

    Update 1
    if you certainly have a drawable defined with the name that is shown in your list, you can update your for cycle as:

    for (int i = 0; i < len; ++i) {
            TextView v = (TextView) view.findViewById(to[i]);
            if (v != null) {
                    v.setText((String) data.get(from[i]));
            }
            ImageView imgV = (ImageView) view.findViewById(to[1]);
            imgV.setImageResource(getResources().getIdentifier((String) 
                data.get(from[i]), "drawable", "yourdefaultpackage"));
        }
    }
    

    just update the yourdefaultpackage part with your application’s default package.

    Update 2

    Below is a detailed sample for how to proceed when you’d like to have different icons for all of the child rows in an expandable list view based on the data the row holds:

    Let’s assume the hierarchical data structure to show is:

    res/raw/data.xml:

    <?xml version="1.0" encoding="UTF-8"?>
    <data>
        <group letter="A">
            <child name="American Bull" img="american_bull" />
            <child name="Arco's" img="arcos" />
        </group>
        <group letter="B">
            <child name="Barter" img="barter" />
            <child name="Bitter B." img="bitter_b" />
            <child name="Bull Hunter" img="bull_hunter" />
            <child name="Bull In Cuba" img="bull_in_cuba" />
            <child name="Bullito" img="bullito" />
        </group>
        <group letter="C">
            <child name="Cackle" img="cackle" />
            <child name="Cheapstake" img="cheapstake" />
            <child name="Checco's Bull" img="checcos_bull" />
            <child name="Cheeriness" img="cheeriness" />
            <child name="Cross Current" img="cross_current" />
            <child name="Cruel" img="cruel" />
        </group>
        <group letter="D"></group>
        <group letter="E"></group>
        <group letter="F">
            <child name="Firearm" img="firearm" />
            <child name="First Of All" img="first_of_all" />
            <child name="First Apple" img="first_apple" />
        </group>
        <group letter="G">
            <child name="Golden" img="golden" />
            <child name="Green Bull" img="green_bull" />
        </group>
        <group letter="H">
            <child name="Hollywood Passion" img="hollywood_passion" />
        </group>
        <group letter="I"></group>
        <group letter="J"></group>
        <group letter="K">
            <child name="Kind Bull" img="kind_bull" />
            <child name="Kingling" img="kingling" />
        </group>
        <group letter="L">
            <child name="Lab" img="lab" />
            <child name="Leary" img="leary" />
            <child name="Leg Pull" img="leg_pull" />
            <child name="Long Bull" img="long_bull" />
            <child name="Lucy" img="lucy" />
        </group>
        <group letter="M">
            <child name="Mayla" img="mayla" />
        </group>
        <group letter="N">
            <child name="New Red Bull Fantasy" img="new_red_bull_fantasy" />
            <child name="Nu Energy" img="nu_energy" />
        </group>
        <group letter="O"></group>
        <group letter="P">
            <child name="Passion" img="passion" />
            <child name="Power" img="power" />
        </group>
        <group letter="Q"></group>
        <group letter="R">
            <child name="Rebellion Red Peach" img="rebellion_red_peach" />
            <child name="Red Bulloska" img="red_bulloska" />
            <child name="Red 28" img="red_28" />
            <child name="Red Bull Wallbanger" img="red_bull_wallbanger" />
            <child name="Red Cell" img="red_cell" />
            <child name="Red Hothead" img="red_hothead" />
            <child name="Red Lime" img="red_lime" />
        </group>
        <group letter="S">
            <child name="Speedy" img="speedy" />
            <child name="Spritz Power" img="spritz_power" />
            <child name="Stiff-Necked" img="stiff_necked" />
        </group>
        <group letter="T"></group>
        <group letter="U"></group>
        <group letter="V">
            <child name="Vedi O' Mare Come E' Bull" img="vedi_o_mare_come_e_bull" />
        </group>
        <group letter="W"></group>
        <group letter="X"></group>
        <group letter="Y"></group>
        <group letter="Z"></group>
        <group letter="#"></group>
    </data>
    

    You need to define your classes to represent this data as java objects. It’s simple, basically you need a Group that has a letter and a list of Child, where Child has a name and an image.
    So you’ll have a Group.java and a Child.java class with the properties above:

    Group.java:

    public class Group
    {
        private String letter;
        private ArrayList<Child> children;
    
        /**
         * @return the letter
         */
        public String getLetter()
        {
            return letter;
        }
    
        /**
         * @param letter the letter to set
         */
        public void setLetter(String letter)
        {
            this.letter = letter;
        }
    
        /**
         * @return the children
         */
        public ArrayList<Child> getChildren()
        {
            return children;
        }
    
        /**
         * @param children the children to set
         */
        public void setChildren(ArrayList<Child> children)
        {
            this.children = children;
        }
    }
    

    Child.java:

    public class Child
    {
        private String name;
        private String image;
    
        /**
         * @return the name
         */
        public String getName()
        {
            return name;
        }
    
        /**
         * @param name the name to set
         */
        public void setName(String name)
        {
            this.name = name;
        }
    
        /**
         * @return the image
         */
        public String getImage()
        {
            return image;
        }
    
        /**
         * @param image the image to set
         */
        public void setImage(String image)
        {
            this.image = image;
        }
    }
    

    To read the xml structure into an ArrayList of Group objects, you will need a simple xml handler too, which will examine the tags, and build up the structure you need:

    XmlHandler.java:

    import java.util.ArrayList;
    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler;
    
    public class XmlHandler extends DefaultHandler
    {
        /**
         * The tag- and attribute names in the xml data
         */
        private static final String TAG_GROUP = "group";
        private static final String TAG_CHILD = "child";
        private static final String ATTR_LETTER = "letter";
        private static final String ATTR_NAME = "name";
        private static final String ATTR_IMG = "img";
    
        /**
         * holds the currently processing Group instance
         */
        private Group currentGroup;
        /**
         * holds the currently processing Child instance
         */
        private Child currentChild;
        /**
         * the list of Group objects parsed from the xml
         */
        private ArrayList<Group> records = null;
    
        /**
         * @return the list of Group parsed from the xml
         */
        public ArrayList<Group> getGroups()
        {
            return records;
        }
    
        @Override
        public void startDocument() throws SAXException
        {
            super.startDocument();
            this.records = new ArrayList<Group>();
        }
    
        @Override
        public void startElement(final String Uri, final String localName, final String qName, 
                final Attributes attributes) throws SAXException
        {
            if (localName == null)
                return;
            if (localName.equals(TAG_GROUP))//examining a group tag
            {
                currentGroup = new Group();
                currentGroup.setLetter(attributes.getValue(ATTR_LETTER));//the letter attribute
                currentGroup.setChildren(new ArrayList<Child>());
                records.add(currentGroup);
            }
            else if (localName.equals(TAG_CHILD))//examining a child tag
            {
                currentChild = new Child();
                currentChild.setName(attributes.getValue(ATTR_NAME));//the name attribute
                currentChild.setImage(attributes.getValue(ATTR_IMG));//the img attribute
                currentGroup.getChildren().add(currentChild);
            }
        }
    }
    

    For displaying a list / expandable list, you need an Adapter class. In this case we’ll use a simple BaseExpandableListAdapter implementation to show the parent and child rows with their proper icons:

    MyExpandableListAdapter.java:

    import java.util.ArrayList;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseExpandableListAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;
    
    public class MyExpandableListAdapter extends BaseExpandableListAdapter
    {
        private final LayoutInflater inflater;
        private final ArrayList<Group> groups;
    
        public MyExpandableListAdapter(LayoutInflater inflater, final ArrayList<Group> groups)
        {
            this.inflater = inflater;
            this.groups = groups;
        }
    
        @Override
        public View getGroupView(int groupPosition, boolean isExpanded, 
                View convertView, ViewGroup parentView)
        {
            final Group parent = groups.get(groupPosition);
            if (convertView == null) //if the row is null, we create it (by inflation)
                convertView = inflater.inflate(R.layout.list_parent, parentView, false);
            // display the letter of the group:
            ((TextView) convertView.findViewById(R.id.rowText1)).
                setText(parent.getLetter());
            // display the children count of the group:
            ((TextView) convertView.findViewById(R.id.rowText2)).
                setText("(" + parent.getChildren().size() + " Ricette)");
            return convertView;
        }
    
        @Override
        public View getChildView(int groupPosition, int childPosition, boolean isLastChild, 
                View convertView, ViewGroup parentView)
        {
            final Group group = groups.get(groupPosition);
            final Child child = group.getChildren().get(childPosition);
            if (convertView == null)//if the child row is null, we inflate it
                convertView = inflater.inflate(R.layout.list_child, parentView, false);
            // display the name of the child on the row:
            ((TextView) convertView.findViewById(R.id.rowText1)).setText(child.getName());
            // set the proper icon of the child on the child row:
            ((ImageView) convertView.findViewById(R.id.photoAlbumImg)).
                setImageResource(parentView.getResources().
                getIdentifier(child.getImage(), "drawable", "com.test.com"));
            return convertView;
        }
    
        @Override
        public Object getChild(int groupPosition, int childPosition)
        {
            return groups.get(groupPosition).getChildren().get(childPosition);
        }
    
        @Override
        public long getChildId(int groupPosition, int childPosition)
        {
            return childPosition;
        }
    
        @Override
        public int getChildrenCount(int groupPosition)
        {
            return groups.get(groupPosition).getChildren().size();
        }
    
        @Override
        public Object getGroup(int groupPosition)
        {
            return groups.get(groupPosition);
        }
    
        @Override
        public int getGroupCount()
        {
            return groups.size();
        }
    
        @Override
        public long getGroupId(int groupPosition)
        {
            return groupPosition;
        }
    
        @Override
        public void notifyDataSetChanged()
        {
            super.notifyDataSetChanged();
        }
    
        @Override
        public boolean isEmpty()
        {
            return ((groups == null) || groups.isEmpty());
        }
    
        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition)
        {
            return true;
        }
    
        @Override
        public boolean hasStableIds()
        {
            return true;
        }
    
        @Override
        public boolean areAllItemsEnabled()
        {
            return true;
        }
    }
    

    Finally, the activity class, which uses the above three:

    testactivity.java:

    import java.util.ArrayList;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    import android.app.ExpandableListActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.MenuItem;
    import android.widget.ExpandableListAdapter;
    
    /**
     * Demonstrates expandable lists using a custom {...@link ExpandableListAdapter} 
     * from {...@link BaseExpandableListAdapter}.
     */
    public class testactivity extends ExpandableListActivity
    {
        ExpandableListAdapter mAdapter;
    
        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.list_main);
            // the next line removes the arrow from the expandable list's group rows,
            // that indicates whether the group is expanded or not.
            // I've removed, because this way it looks nicer.
            getExpandableListView().setGroupIndicator(null);
    
            // read in the list of groups from the xml data
            final ArrayList<Group> groups = readGroupsFromXml();
    
            // Set up our adapter
            mAdapter = new MyExpandableListAdapter(getLayoutInflater(), groups);
            setListAdapter(mAdapter);
            registerForContextMenu(getExpandableListView());
        }
    
        /**
         * Parses the data.xml file located in the /res/raw/ folder, 
         * and builds up the list of Group.
         * @return the list of Group instances to display in the list
         */
        public ArrayList<Group> readGroupsFromXml()
        {
            try
            {
                // initialize our handler
                final XmlHandler handler = new XmlHandler();
                // instantiate a SAXParser for parsing the xml document
                final SAXParser sp = SAXParserFactory.newInstance().newSAXParser();
                // parse the /res/raw/data.xml file 
                // (referenced by R.raw.data) using our handler
                sp.parse(getApplicationContext().getResources().
                        openRawResource(R.raw.data), handler);
                // return the list of Group built inside the handler
                return handler.getGroups();
            }
            catch (Exception e)
            {
                Log.e("Error", "xml", e);
            }
            return null;
        }
    
        // Creo il menu
        @Override
        public boolean onCreateOptionsMenu(Menu menu)
        {
            super.onCreateOptionsMenu(menu);
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.menu, menu);
            return true;
        }
    
        // Creo le azioni per i tasti del menu
        @Override
        public boolean onOptionsItemSelected(MenuItem item)
        {
            super.onOptionsItemSelected(item);
            switch (item.getItemId())
            {
                case R.id.Home:
                    return true;
                case R.id.Cerca:
                    return true;
                case R.id.Glossario:
                    // Inserire azione
                    return true;
                default:
                    return super.onOptionsItemSelected(item);
            }
        }
    }
    

    I hope you can work it out this way.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I've got a string that has curly quotes in it. I'd like to replace
i got an object with contents of html markup in it, for example: string
link Im having trouble converting the html entites into html characters, (&# 8217;) i
Does anyone know how can I replace this 2 symbol below from the string
this is what i have right now Drawing an RSS feed into the php,
I have just tried to save a simple *.rtf file with some websites and
I want to count how many characters a certain string has in PHP, but
I have a JSP page retrieving data and when single or double quotes are
Seemingly simple, but I cannot find anything relevant on the web. What is the
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.