Tuesday, July 23, 2013

Android ExpandableListView Example

The Android Development Tutorials blog contains Basic as well as Advanced android tutorials.Go to Android Development Tutorials to get list of all Android Tutorials.

ExpandableListView

is a view that shows items in a vertically scrolling two-level list. This differs from the ListView by allowing two levels: groups which can individually be expanded to show its children.
Level 1 contains Parent items and Level 2 contains Child items.  The items are filled/populated from the ExpandableListAdapter associated with the Parent and Child view.

In below snapshot Fruits, Flowers, Animals, Birds are Parent Items and Apple,Mango,Banana,Orange,Lion,Tiger etc are Child Items.


ExpandableListView



 ExpandableListView Example

     In this example we will learn how to use ExpandableListView  and how to populate it's item through        ExpandableListAdapter

Steps:
1:  Create xml for Parent Item
2: Create xml for Child Item
3: Create MainActivity and populate the data for Parent and Child Items
4: Create ExpandableListAdapter class and implement getGroupView and getChildView  methods according to your need.

Also add clickListener in getChildView method to handle click events on child items.

Step1:


parent_view.xml

<CheckedTextView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/textViewGroupName"
        android:layout_width="wrap_content"
        android:layout_height="60dp"
        android:layout_marginLeft="5dp"
        android:gravity="center_vertical"
        android:text="@string/hello_world"
        android:textSize="18dp"
        android:textColor="#FFFFFF"
        android:padding="10dp"
        android:textSelectHandleLeft="@string/hello_world"
        android:background="#009999"
        android:textStyle="bold" />

Step 2:


child_view.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:background="#99D6D6"
    android:clickable="true"
    android:orientation="vertical"
    android:paddingLeft="40dp"
    tools:context=".MainActivity" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="39dp"
        android:gravity="center_vertical" >

        <ImageView
            android:id="@+id/childImage"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_margin="5dp"
            android:background="@drawable/ic_launcher"
            android:contentDescription="@string/hello_world" />

        <TextView
            android:id="@+id/textViewChild"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:text="@string/hello_world"
            android:textSize="16sp"
            android:textColor="#1919A3"
            android:textStyle="bold" />
    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@android:color/white" />

</LinearLayout>



ExpandableListView

Step 3:


ExpandableListMainActivity.java

public class ExpandableListMainActivity extends ExpandableListActivity
{
    // Create ArrayList to hold parent Items and Child Items
    private ArrayList<String> parentItems = new ArrayList<String>();
    private ArrayList<Object> childItems = new ArrayList<Object>();

    @Override
    public void onCreate(Bundle savedInstanceState)
    {

        super.onCreate(savedInstanceState);

       
        // Create Expandable List and set it's properties
        ExpandableListView expandableList = getExpandableListView();
        expandableList.setDividerHeight(2);
        expandableList.setGroupIndicator(null);
        expandableList.setClickable(true);

        // Set the Items of Parent

        setGroupParents();
        // Set The Child Data
        setChildData();

        // Create the Adapter
        MyExpandableAdapter adapter = new MyExpandableAdapter(parentItems, childItems);

        adapter.setInflater((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE), this);
       
        // Set the Adapter to expandableList
        expandableList.setAdapter(adapter);
        expandableList.setOnChildClickListener(this);
    }

    // method to add parent Items
    public void setGroupParents()
    {
        parentItems.add("Fruits");
        parentItems.add("Flowers");
        parentItems.add("Animals");
        parentItems.add("Birds");
    }

    // method to set child data of each parent
    public void setChildData()
    {

        // Add Child Items for Fruits

        ArrayList<String> child = new ArrayList<String>();
        child.add("Apple");
        child.add("Mango");
        child.add("Banana");
        child.add("Orange");
       
        childItems.add(child);

        // Add Child Items for Flowers
        child = new ArrayList<String>();
        child.add("Rose");
        child.add("Lotus");
        child.add("Jasmine");
        child.add("Lily");
       
        childItems.add(child);

        // Add Child Items for Animals
        child = new ArrayList<String>();
        child.add("Lion");
        child.add("Tiger");
        child.add("Horse");
        child.add("Elephant");
       
        childItems.add(child);

        // Add Child Items for Birds
        child = new ArrayList<String>();
        child.add("Parrot");
        child.add("Sparrow");
        child.add("Peacock");
        child.add("Pigeon");
       
        childItems.add(child);
    }

}

Step 4:


MyExpandableAdapter.java

public class MyExpandableAdapter extends BaseExpandableListAdapter
{

    private Activity activity;
    private ArrayList<Object> childtems;
    private LayoutInflater inflater;
    private ArrayList<String> parentItems, child;

    // constructor
    public MyExpandableAdapter(ArrayList<String> parents, ArrayList<Object> childern)
    {
        this.parentItems = parents;
        this.childtems = childern;
    }

    public void setInflater(LayoutInflater inflater, Activity activity)
    {
        this.inflater = inflater;
        this.activity = activity;
    }
   
    // method getChildView is called automatically for each child view.
    //  Implement this method as per your requirement
    @Override
    public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent)
    {

        child = (ArrayList<String>) childtems.get(groupPosition);

        TextView textView = null;

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.child_view, null);
        }
   
         // get the textView reference and set the value
        textView = (TextView) convertView.findViewById(R.id.textViewChild);
        textView.setText(child.get(childPosition));

        // set the ClickListener to handle the click event on child item
        convertView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                Toast.makeText(activity, child.get(childPosition),
                        Toast.LENGTH_SHORT).show();
            }
        });

        return convertView;
    }

    // method getGroupView is called automatically for each parent item
    // Implement this method as per your requirement
    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
    {

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.parent_view, null);
        }

        ((CheckedTextView) convertView).setText(parentItems.get(groupPosition));
        ((CheckedTextView) convertView).setChecked(isExpanded);

        return convertView;
    }

    @Override
    public Object getChild(int groupPosition, int childPosition)
    {
        return null;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition)
    {
        return 0;
    }

    @Override
    public int getChildrenCount(int groupPosition)
    {
        return ((ArrayList<String>) childtems.get(groupPosition)).size();
    }

    @Override
    public Object getGroup(int groupPosition)
    {
        return null;
    }

    @Override
    public int getGroupCount()
    {
        return parentItems.size();
    }

    @Override
    public void onGroupCollapsed(int groupPosition)
    {
        super.onGroupCollapsed(groupPosition);
    }

    @Override
    public void onGroupExpanded(int groupPosition)
    {
        super.onGroupExpanded(groupPosition);
    }

    @Override
    public long getGroupId(int groupPosition)
    {
        return 0;
    }

    @Override
    public boolean hasStableIds()
    {
        return false;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition)
    {
        return false;
    }

}




ExpandableListView




 

New Advance Topics:                   Android LiveWallpaer Tutorial
Android ImageSwitcher                    Android TextSwitcher                                Android ViewFlipper
Android Gesture Detector               Handling/Detecting Swipe Events                Gradient Drawable
Detecting Missed Calls                    Hide Title Bar                                           GridView Animation
Android AlarmManager                 Android BootReceiver                       Vibrate Phone In a Desirable Pattern    
Developing for Different Screen Sizes           Showing Toast for Longer Time       Publishing your App
How to publish Android App on Google Play
Android TextWatcher                               Android ExpandableListView

 Beginning With Android
      Android : Introduction(What is Android)                                                              Configuring Eclipse for Android Development
     Creating Your First Android Project                                           Understanding Android Manifest File of your android app

 Advance Android Topics                                                              Customizing Android Views


Working With Layouts                                                                Working With Views

Understanding Layouts in Android                                                   Using Buttons and EditText in Android
Working with Linear Layout (With Example)                                     Using CheckBoxes in Android
Nested Linear Layout (With Example)                                              Using AutoCompleteTextView in Android                                                                                          Grid View
Relative Layout In Android                                                               ListView
Table Layout                                                                                   Android ProgressBar
Frame Layout(With Example)                                                          Customizing ProgressBar
Absolute Layout                                                                             Customizing Radio Buttons
Grid Layout                                                                                    Customizing Checkboxes In Android

Android Advance Views
Android Spinner                                                                           Android GalleryView
Android TabWidget                                                                      Android ExpandableListView

Android Components                                                                 Dialogs In Android

Activity In Android                                                                    Working With Alert Dialog
Activity Life Cycle                                                                    Adding Radio Buttons In Dialog
Starting Activity For Result                                                       Adding Check Boxes In Dialog
Sending Data from One Activity to Other in Android                    Creating Customized Dialogs in Android
Returning Result from Activity                                                   Creating Dialog To Collect User Input
Android : Service                                                                     DatePicker and TimePickerDialog
BroadcastReceiver                                                                   Using TimePickerDialog and DatePickerDialog In android

Menus In Android                                                                ListView:
Creating Option Menu                                                               Populating ListView With DataBase
Creating Context Menu In Android                                              Populating ListView with ArrayList
                                                                                               ListView with Custom Adapter

Toast                                                                                      Working With SMS
Customizing Toast In Android                                                       How to Send SMS in Android
Customizing the Display Time of Toast                                        How To Receive SMS
Customizing Toast At Runtime                                                  Accessing Inbox In Android
Adding Image in Toast
Showing Toast for Longer Time


TelephonyManager                                                            Storage: Storing Data In Android
Using Telephony Manager In Android                                          SharedPreferences In Android
                                                                                              Reading and Writing files to Internal Stoarage

Working With Incoming Calls                                       DataBase :  Introduction of SQLiteDataBase
How To Handle Incoming Calls in Android                                Working With Database in Android
How to Forward an Incoming Call In Android                            Creating Table In Android
CALL States In Android                                                          Inserting, Deleting and Updating Records In Table in Android


Miscellaneous
Notifications In Android
How To Vibrate The Android Phone
Sending Email In Android
Opening a webpage In Browser
How to Access PhoneBook In Android
Prompt User Input with an AlertDialog
How to Hide Title Bar In Android
How to show an Activity in Landscape or Portrait Mode only.
How to Set an Image as Wallpaper.






41 comments:

  1. Very Nice tutorial, Well Explained.

    ReplyDelete
  2. Thanks for this tutorial, pls how I make the child to have another sub-child? Also, how can I make the child or sub-child to link to another page...Am still new in android developing...

    ReplyDelete
  3. Thanks for the tutorial. How can a child be link to another page.

    ReplyDelete
  4. thanks for the tutorial.. how can I make a child when click to open new activity instead of Toast...

    ReplyDelete
  5. I want's learn about sqlite database in android

    ReplyDelete
    Replies
    1. Follow the link http://www.learnandroideasily.blogspot.in/2013/07/sqlitedatabase-in-android.html to learn about SQLite DataBase

      Delete
  6. Am having problem to make each child to open new activity when click, pls can u help me to write the code that when a particular child is click, it will open new activity like using intent. Am new bee in android

    ReplyDelete
  7. Thank you so much for this! I've been trying to wrap my head around this concept, and how to make it work, for a couple weeks now. I've looked through a few other examples, and this one finally connected the dots in my head.

    My next step is to load the lists from a database...

    ReplyDelete
  8. Its a very nice written article, i have only one question if i want to deleted the parent with its child how to do that? kindly guide me

    ReplyDelete
  9. How to add searching in it by edittext?

    ReplyDelete
  10. its a very nice article, but i have a question..... how edit XML (add button and text) ???. Regards

    ReplyDelete
  11. Very nice article but i have a question, how edit XML file. I need add button and text. Regards

    ReplyDelete
  12. I have a problem in the click event on child item.Show text diferent on click field.

    ReplyDelete
  13. Nice tutorial. I have doubt, When flowers list been selected, how to hide fruits list?

    ReplyDelete
  14. Nice tutorial. How to hide fruit list, when flowers list been selected?

    ReplyDelete
  15. Nice tutorial. So helpful for me

    ReplyDelete
  16. Thank You very Much... very nice article..

    ReplyDelete
  17. Hi, the only thing I would change here is setting the layout inflater like this inside the constructor of the adapter:
    setInflater(getLayoutInflater(), this);

    I had a resource leak and this fixed it

    ReplyDelete
  18. Hi ,
    I went to change this
    // method to add parent Items
    public void setGroupParents()
    {
    parentItems.add("Fruits");
    parentItems.add("Flowers");
    parentItems.add("Animals");
    parentItems.add("Birds");
    }

    // method to set child data of each parent
    public void setChildData()
    {

    // Add Child Items for Fruits
    ArrayList child = new ArrayList();
    child.add("Apple");
    child.add("Mango");
    child.add("Banana");
    child.add("Orange");

    childItems.add(child);

    // Add Child Items for Flowers
    child = new ArrayList();
    child.add("Rose");
    child.add("Lotus");
    child.add("Jasmine");
    child.add("Lily");

    childItems.add(child);

    // Add Child Items for Animals
    child = new ArrayList();
    child.add("Lion");
    child.add("Tiger");
    child.add("Horse");
    child.add("Elephant");

    childItems.add(child);

    // Add Child Items for Birds
    child = new ArrayList();
    child.add("Parrot");
    child.add("Sparrow");
    child.add("Peacock");
    child.add("Pigeon");

    childItems.add(child);
    }

    }

    to
    values/strings

    How to change ?

    ReplyDelete
  19. I have been surfing online more than 4 hours today,
    yet I never found any interesting article like yours. It's pretty worth enough for me.

    Personally, if all website owners and bloggers made
    good content as you did, the net will be much more useful than ever before.

    ReplyDelete
  20. casinos online
    online casino real money
    play casino games online
    online casino real money
    online casino games

    ReplyDelete
  21. Spamming is a irritating problem of my blogging life.

    ReplyDelete
  22. At this time it looks like Wordpress is the preferred blogging platform available right now.
    (from what I've read) Is that what you are using on your blog?

    ReplyDelete
  23. Thanks for a marvelous posting! I quite enjoyed reading it, you may be a great author.
    I will always bookmark your blog and will often come
    back down the road. I want to encourage continue your great posts,
    have a nice day!

    ReplyDelete
  24. Is there some secret psychology behind catapulting irate birds at snarky little pigs.

    As soon as they had received the graphics that they had requested through the graphics department, they
    did start to build the modern areas. Visual displays may be designed to show any airport
    or terrain on the globe through the flight simulator.

    ReplyDelete
  25. So there's clearly no great virtual airline ticket price
    benefit due to virtual airline deregulation. Playing free addicting games or any game accessible on the net
    can actually provide enjoyment for the household.
    " Picking a quarterback who is able to help facilitate the startup process with your startup team is essential for proper coordination.

    ReplyDelete
  26. The portal is giving to its clients a number of the authentic information to help them to play bingo in their fashion. You should then look to start out to check out the kind of the
    remainder players. The owners of this network devise that
    rule whose top most priority is to give immense happiness towards the
    clients.

    ReplyDelete
  27. Tính năng này hiện không có. Vui lòng thử lại sau.

    ReplyDelete
  28. But, 2010 is special for Delhi and thousands of sports persons, who are likely to come
    here and take part in the games. Perhaps the most potent spelling word games is usually
    to challenge your sons or daughters to publish their unique
    folk stories, original poetry, or musicals
    using a huge quantity of their words. Visual displays could be designed to show any airport or terrain on the planet over the flight simulator.

    ReplyDelete
  29. The people entering these searches are generally people trying to find chances to experience the said high bets roulette about the Internet,
    or people trying to know the procedure of playing
    such high roulette online. Since the action has massive
    followers worldwide it's not surprising a large number of searches about
    roulette strategies and tips are whipped out.

    In fact, it may be better to perhaps look at the source
    and turn into assured of the validity before you can actually make use of the information for anything as such.

    ReplyDelete
  30. Também são comuns durante atividades físicas.

    ReplyDelete
  31. Link exchange is nothing else however it is just placing the other person's weblog link on your
    page at suitable place and other person will also do same
    in favor of you.

    ReplyDelete
  32. Spot on with this write-up, I absolutely believe this web site needs a lot more attention. I'll probably be returning to read
    more, thanks for the information!

    ReplyDelete
  33. Hi, I do believe this is a great blog. I stumbledupon it ;) I will
    return yet again since I book-marked it. Money and freedom is the greatest way
    to change, may you be rich and continue to guide others.

    ReplyDelete
  34. Ridiculous story there. What happened after? Good luck!

    ReplyDelete