Android Add Views into a ViewGroup Dynamically

As Android developer you will surely  need someday to add views dynamically, instead of creating a ListView. I will show you in this tutorial how to do this 🙂

1. Create a new project and call your activity “MyActivity”
2. Go to res – layout – main.xml and put the following code:

3. Go to res – layout and create a new xml called text_layout.xml and put the following code:

4. Now go to MyActivity class and put the following code:

And now you should have a list with 100 rows that can be scrolled.

Android Expandable List Example

In this tutorial I will show you how to make a simple Expandable List.

1. Create a new project and call your java class(the one that is generated by Eclipse or other IDE) “MyActivity”.

2. Go to res – layout -main.xml and put the following code:

NOTE: The attribute “android:transcriptMode=”alwaysScroll”” will make your expandable list always to scroll to the end of the list when you want to expand or collapse a group. If you do not want this set it this way: “android:transcriptMode=”disabled“. Now when you expand a group the list will scroll to the group that is expanded.

3. Now create another 2 xml files in res – layout,  one called list_item_parent.xml and the other one called list_item_child.xml.

  • The xml code for list_item_parent.xml file is:

NOTE: If you put a button on the parent the group will not expand anymore, so in order to make the group expand when you have a button you must set its focus to FALSE. Also, if that doesn’t work, it should work with:

 

  • The xml code for list_item_child.xml file is:

4. Now create a new java class and call it “Parent”. In this class we will store the data about the parent: the  name and the children (an array list of children). After you create the class put the following code:

5. At this step you have to create the adapter for the expandable list. To do this, create a new java class called “MyCustomAdapter” and put the following code:

6. Now go to the MyActivity and put the following code:

Now the result should look like this:

If you want to see the source code, please visit our GitHub repo here. There you can see a working project that might help you get started with ExpandableListView.