Android development-expandablelistview

Source: Internet
Author: User

/*

* Android development-expandablelistview

* Beijing Android Club group: 167839253

* Created on: 2012-7-23

* Author: blueeagle

* Email: liujiaxiang@gmail.com

*/

Sometimes, using listview does not meet the functions required by the application. Some applications require multiple sets of listview. In this case, we need to use a new control, expandablelistview, which can be extended. It groups listview. It's like when we use QQ, there are "My Friends", "strangers", and "blacklists". Clicking it will expand, and clicking it will shrink back.

Expandablelistview is a view that shows two levels of list items vertically. Unlike listview, expandablelistview can have two layers: each layer can be expanded independently and its subitems are displayed. These subitems are from the expandablelistadapter associated with the view.

Each list item that can be expanded has an indicator (arrow) next to it to indicate the status before the list item (these statuses are generally list items that have been expanded, there are no extended list items, sub-list items and the last sub-list items ). You can use setchildindicator (drawable) and setgroupindicator (drawable) to set the style of these indicators. You can also use the default indicator. Deploy Android. R. layout. simple_expandable_list_item_1, Android. R. layout. simple_expandable_list_item_2

Like listview, expandablelistview is also a control that requires an adapter as a bridge to obtain data. Generally, the adapter that applies to expandablelistview must inherit the baseexpandablelistadapter class, And the getgroupview and getchildview methods must be reloaded.

The main methods to overload baseexpandablelistadapter are as follows:

Public abstract objectgetchild (INT groupposition, int childposition)

Obtains the data associated with the specified group and specified sub-project.

Parameters

Groupposition: the position of the Group that contains the sub-view.

The position of the subview in the group specified by childposition.

Return

The data associated with the subview.

Public abstract long getchildid (INT groupposition, intchildposition)

Obtain the ID of the Child view in the given group. The group ID must be unique in the group. It must be different from all other IDS (group and subitem ID ).

Parameters

Groupposition: the position of the Group that contains the sub-view.

Childposition: the position of the subview in the specified group where the ID is to be obtained.

Return

Id associated with the subview.

Public abstract view getchildview (INT groupposition, intchildposition, Boolean islastchild, view convertview, viewgroup parent)

Obtains the view used to display the data of a given group to the sub-location.

Parameters

Groupposition contains the group location for obtaining the subview.

The position of the Child view in the childposition group (view to be returned.

Islastchild: whether the view is the last view in the group.

If convertview is possible, reuse the old view object. before use, make sure that the view object is not empty and is of the appropriate type. if the object cannot be converted to a view that correctly displays data, this method creates a new view. the view previously created by getchildview (INT, Int, Boolean, view, viewgroup) is not guaranteed.

Parent: the parent view that the view ultimately belongs.

Return

The child view corresponding to the specified position.

Public abstract int getchildrencount (INT groupposition)

Obtains the sub-prime number of a specified group.

Parameters

Groupposition: The group location where the number of child elements is to be obtained.

Return

Number of sub-elements in a group.

Public abstract long getcombinedchildid (long groupid, long childid)

Obtain the ID (including group ID and sub-entry ID) of the subentry that can be uniquely identified in the list ). the extensible list requires that each entry (Group Entry and sub-entry) has a unique ID that identifies the subentry and sub-entry in the list. this method returns a unique identification ID based on the subentry ID and the Group Entry ID. in addition, if hasstableids () is true, the IDS returned by this function must be fixed.

Parameters

Group Entry ID whose groupid contains the sub-entry ID.

ID of the Child entry of childid.

Return

You can uniquely identify the ID of a sub-entry in all Group Entries and sub-entries (which may be fixed ).

Public abstract long getcombinedgroupid (long groupid)

Obtain the ID (including group ID and sub-entry ID) of the subentry that can be uniquely identified in the list ). the extensible list requires that each entry (Group Entry and sub-entry) has a unique ID that identifies the subentry and sub-entry in the list. this method returns a unique identification ID based on the subentry ID and the Group Entry ID. in addition, if hasstableids () is true, the IDS returned by this function must be fixed.

Parameters

Groupid Group Entry ID.

Return

You can uniquely identify the IDs of all group entries and sub-entries (which may be fixed ).

Public abstract object getgroup (INT groupposition)

Obtains the data associated with the specified group.

Parameters

The position of the groupposition group.

Return

Data of the specified group.

Public abstract int getgroupcount ()

Obtain the number of groups.

Return

Number of groups.

Public abstract long getgroupid (INT groupposition)

Obtain the ID of the specified group. The group ID must be unique in the group. It must be different from all other IDS (group and subitem ID ).

Parameters

Groupposition: The group location where the ID is to be obtained.

Return

Id associated with the group.

Public abstract view getgroupview (INT groupposition, booleanisexpanded, view convertview, viewgroup parent)

Obtains the view used to display a given group. this method only returns the view object of the group. To obtain the view object of the child element, you need to call getchildview (INT, Int, Boolean, view, viewgroup ).

Parameters

Groupposition determines the Group position of the returned view.

Isexpanded: whether to expand or collapse the group.

If convertview is possible, reuse the old view object. before use, make sure that the view object is not empty and is of the appropriate type. if the object cannot be converted to a view that correctly displays data, this method creates a new view. the view created by getgroupview (INT, Boolean, view, and viewgroup) is not guaranteed.

Parent: the parent view that the view ultimately belongs.

Return

The Group view corresponding to the specified position.

Public Abstract Boolean hasstableids ()

Whether to specify the background data change corresponding to the ID of the Group view and its subview will also maintain this ID.

Return

Whether the same ID always points to the same object.

Public Abstract Boolean ischildselectable (INT groupposition, intchildposition)

Whether the subview of the specified position can be selected.

Parameters

Groupposition contains the group location for obtaining the subview.

The position of the Child view in the childposition group.

Return

Whether the sub-view is selectable.

Note:

In the XML layout file, if the size of the first-level view on the expandablelistview is not strictly defined, the value of wrap_content cannot be used for the Android: layout_height attribute of the expandablelistview. (For example, if the previous view is a scrollview, you should not specify the value of wrap_content because it can be of any length. However, if the upper-level view of the expandablelistview has a specific size, for example, 100 pixels, you can use wrap_content)

If the value of wrap_content is specified for expandablelistview due to carelessness during development, a null pointer error at setcontentview is reported.

Based on the description, Let's first look at a simple example:

The code for defining XML is as follows:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <ExpandableListView           android:id = "@+id/myExpandableListView"        android:layout_width="fill_parent"                          android:layout_height="fill_parent"                        android:layout_weight="1"                         />   </LinearLayout>

An expandablelistview is arranged in linearlayout.

The code in Java is as follows:

/** Android development: expandablelistview * Beijing Android Club group: 167839253 * created on: * expandablelistviewactivity. java * Author: blueeagle * Email: liujiaxiang@gmail.com */package COM. blueeagle. WWW; import Java. util. arraylist; import Java. util. list; import android. app. activity; import android. OS. bundle; import android. view. gravity; import android. view. view; import android. view. viewgroup; import android. widge T. abslistview; import android. widget. baseexpandablelistadapter; import android. widget. expandablelistview; import android. widget. textview; public class expandablelistviewactivity extends activity {private list <string> groupdata; // defines the private list of group data <list <string> childrendata; // define the private void loadlistdate () {groupdata = new arraylist <string> (); groupdata. add ("country"); groupdata. add ("character"); groupdat A. add ("Weapon"); childrendata = new arraylist <list <string> (); List <string> Child1 = new arraylist <string> (); child1.add (""); child1.add ("Wei Guo"); child1.add ("Wu Guo"); childrendata. add (Child1); List <string> child2 = new arraylist <string> (); child2.add ("Guan Yu"); child2.add ("Zhang Fei"); child2.add ("dianwei "); child2.add ("LV Bu"); child2.add ("Cao"); child2.add ("Gan Ning"); child2.add ("guo jia"); child2.add ("Zhou Yu"); childrendata. add (child2 ); List <string> Child3 = new arraylist <string> (); child3.add ("Qinglong yanyue knife"); child3.add ("zhangba snake gun "); child3.add ("qinggang "); child3.add ("Qilin "); child3.add ("yinyue gun"); childrendata. add (Child3) ;}@ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); loadlistdate (); expandablelistview myexpandablelistview = (expandablelistview) findviewbyid (R. id. Myexpandablelistview); myexpandablelistview. setadapter (New expandableadapter ();} private class expandableadapter extends baseexpandablelistadapter {@ overridepublic object getchild (INT groupposition, int childposition) {return childrendata. get (groupposition ). get (childposition) ;}@ overridepublic long getchildid (INT groupposition, int childposition) {return 0 ;}@ overridepublic view getchildview (int Groupposition, int childposition, Boolean islastchild, view convertview, viewgroup parent) {textview mytext = NULL; If (convertview! = NULL) {mytext = (textview) convertview; mytext. settext (childrendata. get (groupposition ). get (childposition);} else {mytext = createview (childrendata. get (groupposition ). get (childposition);} return mytext;} @ overridepublic int getchildrencount (INT groupposition) {return childrendata. get (groupposition ). size () ;}@ overridepublic object getgroup (INT groupposition) {return groupdata. get (groupposition) ;} @ Overridepublic int getgroupcount () {return groupdata. size () ;}@ overridepublic long getgroupid (INT groupposition) {return 0 ;}@ overridepublic view getgroupview (INT groupposition, Boolean isexpanded, view convertview, viewgroup parent) {textview mytext = NULL; If (convertview! = NULL) {mytext = (textview) convertview; mytext. settext (groupdata. get (groupposition);} else {mytext = createview (groupdata. get (groupposition) ;}return mytext ;}@ overridepublic Boolean hasstableids () {return false ;}@ overridepublic Boolean ischildselectable (INT groupposition, int childposition) {return false ;} private textview createview (string content) {abslistview. layoutparams = new abslistview. layoutparams (viewgroup. layoutparams. fill_parent, 80); textview mytext = new textview (expandablelistviewactivity. this); mytext. setlayoutparams (layoutparams); mytext. setgravity (gravity. center_vertical | gravity. left); mytext. setpadding (80, 0, 0, 0); mytext. settext (content); Return mytext ;}}}

Shows the effect:

This completes a simple expandablelistview control.

In actual development, there are often different requirements. For example, each child needs different controls, each group or child needs icons, and the icon display needs to be different, we need to set the background and various other requirements that will make our programs beautiful. Next we will discuss how expandablelistview can meet these requirements one by one.

For example, if you set the background for expandablelistview, expand group N by default, and count N from 0, you only need to add the following code:

myExpandableListView.setBackgroundResource(R.drawable.background);myExpandableListView.expandGroup(0);

The effect is as follows:

Change the icon in front of each group, and the icon style varies with the combination and expansion, you only need to define the file: Indicator. XML in the Res/drawable directory

<selector xmlns:android="http://schemas.android.com/apk/res/android">      <item android:state_expanded="true" android:drawable="@drawable/right" />      <item android:drawable="@drawable/down"></item>  </selector>

Add the following content to the Java file:

myExpandableListView.setGroupIndicator(this.getResources().getDrawable(R.drawable.indicator));

The effect is as follows:

For other attribute settings, refer to the following attributes:

Android: childdivider

The image or color of the ion list item. Note: The image is not completely displayed, and the list of ions is a straight line.

Android: childindicator

Indicator displayed next to the sub-list item. Note: It can be an image.

Android: childindicatorleft

The left constraint position of the sub-list item indicator. Note: Counting starts from 0 on the left side. For example, if the indicator is an icon and the value of this attribute is set to 3dip, the icon is displayed starting from 3dip on the left side.

Android: childindicatorright

The constraint position on the right of the sub-list item indicator. Note: indicates the end of the right end

Android: groupindicator

Indicator displayed next to the group list item. Note: It can be an image.

Android: indicatorleft

The left constraint position of the group list item indicator. Note: the position where the left end starts.

Android: indicatorright

The constraint position on the right of the group list item indicator. Note: It indicates the end of the right end.

 

Of course, you can also use custom views to describe group and child. Custom views can be written in the layout folder like layout files. For example, name group. xml or child. xml.

For example, if we define a child item to consist of an imageview and a textview, we can define child. XML:

<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:orientation = "horizontal"android:layout_width="match_parent"android:layout_height="match_parent"><ImageViewandroid:layout_gravity = "center_vertical"android:id = "@+id/imageView01"android:layout_width = "70px"android:layout_height = "70px"android:paddingLeft = "30px"android:paddingTop = "2px"android:paddingBottom = "5px"android:src = "@drawable/ic_launcher"/><TextViewandroid:layout_gravity = "center_vertical"android:id = "@+id/childTV"android:layout_width = "match_parent"android:layout_height = "match_parent"android:paddingLeft = "30px"android:paddingTop = "10px"android:paddingBottom = "5px"android:textSize = "30sp"/></LinearLayout>

The attributes are not described in detail.

Data in expandablelistview can also be defined as follows:

List <Map <string, string> groups = new arraylist <Map <string, string> (); Map <string, string> group1 = new hashmap <string, string> (); group1.put ("group", "country ");...... Groups. Add (group1 );...... // Prepare the second-level list data in the first level-1 List: three second-level lists, which display the "Wei Guo", "Shu Guo", and "Wu Guo" list <Map <string, string> Child1 = new arraylist <Map <string, string> (); Map <string, string> child1data1 = new hashmap <string, string> (); child1data1. put ("child", "Wei Guo ");...... Child1.add (child1data1 );...... // Prepare the level-2 List data in the second level-1 List: eight level-2 lists, display "Guan Yu", "Zhang Fei", "dianwei", "Lu Bu", "Cao", "Gan Ning", "guo jia", "Zhou Yu" list <Map <string, string> child2 = new arraylist <Map <string, string> (); Map <string, string> child2data1 = new hashmap <string, string> (); child2data1. put ("child", "Guan Yu ");...... Child2.add (child2data1 );...... // Prepare the level-2 List data in the third level-1 List: five level-2 lists, display "Qinglong yanyue knife", "zhangba snake gun", "qinggang sword", "Qilin bow", "yinyue gun" list <Map <string, string> Child3 = new arraylist <Map <string, string> (); Map <string, string> child3data1 = new hashmap <string, string> (); child3data1. put ("child", "Qinglong yanyue Dao ");...... Child3.add (child3data1 );...... // Use a list object to save all list-Level list data list <Map <string, string> Childs = new arraylist <list <Map <string, string >>> (); Childs. add (Child1); Childs. add (child2); Childs. add (Child3); Modify the Java file for the data definition method described above: for example, write the following code in the getchildview function, string text = groups. get (groupposition ). get ("group"); layoutinflater = (layoutinflater) context. getsystemservice (context. layout_inflater_service); // gets the layout file of the first-level list and sets the corresponding element attribute linearlayout = (linearlayout) layoutinflater. inflate (R. layout. group, null); textview = (textview) linearlayout. findviewbyid (R. id. textview01); textview. settext (text); Return linearlayout;

In this way, you can write the custom view to child. Of course, you can also define the view without a layout file, or you can implement the view by yourself using code.

Additional knowledge:

For expandablelistview, there is also an expandablelistactivity that corresponds to it. For an activity that only needs an expandablelistview, you only need to use expandablelistactivity to complete the corresponding functions. Note that the following code is added to the main. XML page:

<Listview Android: Id = "@ Android: ID/List" or Android: Id = "@ ID/Android: List" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content"> </listview>

This ID cannot be changed at will; otherwise, an exception occurs: Java. Lang. runtimeexception: Your content must have a expandablelistview whose ID attribute is 'android. R. Id. list '.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.