Académique Documents
Professionnel Documents
Culture Documents
implementar las interfaces de nuestras apps, entre ellas se encuentra la que pasamos a
ensearos hoy y que nos proporciona una manera elegante de mostrar listados de datos
agrupados de una forma ordenada.
Normalmente usaremos un ListView para mostrar los datos pero si la cantidad de estos es
excesiva y tenemos la posibilidad de agruparlos mediante algn criterio una opcin muy a
tener en cuenta seria usar ExpandableListView que es la vista que a continuacin os
vamos a ensear a usar:
1
2
3
4
ExpandableListAdapter mAdapter;
ExpandableListView epView = (ExpandableListView) indViewById(R.id.ExpandableListV
mAdapter = new MyExpandableListAdapter();
epView.setAdapter(mAdapter);
Al igual que ListView y cualquier AdapterView deberemos usar un adapter que gestione la
coleccin de datos que mostraremos, aqu os dejamos un ejemplo de uno:
?
1
2
3
4
/**
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
*/
public class MyExpandableListAdapter extends BaseExpandableListAdapter {
// Sample data set. children[i] contains the children (String[]) for
// groups[i].
private String[] groups = { "Parent1", "Parent2",
"Parent3" };
private String[][] children = { { "Child1" },{ "Child2" }, { "Child3" },{ "Chi
public Object getChild(int groupPosition, int childPosition) {
return children[groupPosition][childPosition];
}
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
public int getChildrenCount(int groupPosition) {
int i = 0;
try {
i = children[groupPosition].length;
} catch (Exception e) {
}
return i;
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
}
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
TextView textView = getGenericView();
textView.setText(getGroup(groupPosition).toString());
return textView;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public boolean hasStableIds() {
return true;
}
}
En este ejemplo generamos las vistas tanto del Parent como del Child mediante cdigo,
pero no habra ningn problema en generarlas a partir de archivos xml. Aqu un ejemplo:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
PASO 3 Listeners
Por ltimo implementaremos los mtodos que aadirn la funcionalidad a los elementos
del listado:
?
1
2
3
4
5
6
7
8
9
1 epView.setOnGroupClickListener(new OnGroupClickListener() {
@Override
0
public boolean onGroupClick(ExpandableListView arg0, View arg1,
11
int groupPosition, long arg3) {
1
if (groupPosition == 5) {
2
1
}
3
1
// Aqui podriamos cambiar si quisieramos el comportamiento de apertura y ci
4 expandGroup(int groupPos)
1
return false;
5
}
1
});
6
1
epView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
7
@Override
public boolean onChildClick(ExpandableListView parent,
1
View v, int groupPosition, int childPosition,
8
long id) {
1
if (groupPosition == 0 && childPosition == 0) {
9
2
}
0
return false;
2
}
1
});
2
2
2
3
2
4
2
5
2
6
PASO 4 Personalizacin
Mediante xml podemos configurar ciertos aspectos grficos como los divisores del listado o
los indicadores. Podis ver el listado completo en la documentacin oficial. A continuacin
os contamos como crear nuestro propio groupIndicator.
android:groupIndicator="@null"
1
2
3
4
5
<selectorxmlns:android="http://schemas.android.com/apk/res/android">
<itemandroid:state_empty="true"android:drawable="@android:color/transparent"/
<itemandroid:state_expanded="true"android:drawable="@drawable/my_icon_max"/>
<itemandroid:drawable="@drawable/my_icon_min"/>
</selector>
Y con esto hemos terminado, con un poco de maa e imaginacin se pueden conseguir
resultados muy vistosos como el que os mostramos de nuestra prximas app:
android:layout_height="fill_parent"/>
android:id="@+id/simpleExpandableListView"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:divider="#f00"
android:dividerHeight="1dp" /> "/> <!-- red color divider with 1dp height between
the groups items of expandable list view -->
android:listSelector="#0f0" /> <!-- green color for the list selector item -->
an
the
Adapter
that
links
a
underlying
data.
The
@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
@Override
public int getGroupCount() {
return 0;
}
@Override
public int getChildrenCount(int groupPosition) {
return 0;
}
@Override
public Object getGroup(int groupPosition) {
return null;
}
@Override
public Object getChild(int groupPosition, int childPosition) {
return null;
}
@Override
public long getGroupId(int groupPosition) {
return 0;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return 0;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView,
ViewGroup parent) {
return null;
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
View convertView, ViewGroup parent) {
return null;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return false;
}
@Override
@Override
public boolean isEmpty() {
return false;
}
@Override
public void onGroupExpanded(int groupPosition) {
@Override
public void onGroupCollapsed(int groupPosition) {
@Override
public long getCombinedChildId(long groupId, long childId) {
return 0;
}
@Override
public long getCombinedGroupId(long groupId) {
return 0;
}
}
then
extends
@Override
public int getGroupCount() {
return 0;
}
@Override
public int getChildrenCount(int groupPosition) {
return 0;
}
@Override
public Object getGroup(int groupPosition) {
return null;
}
@Override
public Object getChild(int groupPosition, int childPosition) {
return null;
}
@Override
public long getGroupId(int groupPosition) {
return 0;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return 0;
@Override
public boolean hasStableIds() {
return false;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView,
ViewGroup parent) {
return null;
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
View convertView, ViewGroup parent) {
return null;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return false;
}
}
In
Android
3. SimpleExpandableListAdapter:
SimpleExpandableListAdapter is an adapter that is used to map
the static data to group and child views defined in our XML
( layout ) file. We can separately specify the data backing to the
group as a List of Maps. Each entry in a ArrayList corresponds to
one group in the Expandable List. The maps contains the data
for each row. We can also specify an XML file that defines the
views used to display a group, and a mapping from keys in the
Map to specific views. This process is similar for a child, except it
is one level deeper so the data backing is specified as a
Step
1: Create
a
new
ExpandableListViewExample.
project and
name
it
<ExpandableListView
android:id="@+id/simpleExpandableListView"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:divider="#f00"
android:childDivider="#0f0"
android:dividerHeight="1dp" />
</RelativeLayout>
Step 3: Create a new xml file for group items Open res ->
layout -> group_items.xml and add following code:
In this step we add the code for displaying a TextView subject
names.
<?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="55dip"
android:orientation="vertical" >
<TextView
android:id="@+id/heading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="35sp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textStyle="bold" />
</LinearLayout>
Step 4: Create a new xml file for group items Open res ->
layout -> child_items.xml and add following code:
In this step we add the code for displaying two TextView i.e. one
for sequence of topics and another for topic name
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:id="@+id/sequence"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:paddingLeft="35sp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/childItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="@id/sequence"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.LinkedHashMap;
private
LinkedHashMap<String,
LinkedHashMap<String, GroupInfo>();
GroupInfo>
subjects
new
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
(ExpandableListView)
return false;
}
});
addProduct("Android","ListView");
addProduct("Android","ExpandableListView");
addProduct("Android","GridView");
addProduct("Java","PolyMorphism");
addProduct("Java","Collections");
int groupPosition = 0;
package
>
In this step, we create a class for setting and getting the group
item name and child items info according to a particular group.
GroupInfo is a model class used to set the name of the group
item and child items information from your main activity and
then get the information within Adapter class. Finally set the
value to ExpandableListView.
package example.abhiandroid.expandablelistviewexample;
import java.util.ArrayList;
>
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Gourav on 08-03-2016.
*/
public class CustomAdapter extends BaseExpandableListAdapter {
@Override
public Object getChild(int groupPosition, int childPosition) {
ArrayList<ChildInfo>
deptList.get(groupPosition).getProductList();
productList
return productList.get(childPosition);
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
View view, ViewGroup parent) {
(LayoutInflater)
return view;
}
@Override
public int getChildrenCount(int groupPosition) {
ArrayList<ChildInfo>
deptList.get(groupPosition).getProductList();
productList
return productList.size();
@Override
public Object getGroup(int groupPosition) {
return deptList.get(groupPosition);
}
@Override
public int getGroupCount() {
return deptList.size();
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public View getGroupView(int groupPosition, boolean isLastChild, View view,
ViewGroup parent) {
(LayoutInflater)
return view;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}