Skip to main content

Custom Expandable ListView(Android)

Here is the example of customize ExpandableListview:
 
 
MainActivity.java
 
importjava.util.ArrayList;
importjava.util.LinkedHashMap;
importandroid.app.Activity;
importandroid.os.Bundle;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.widget.ArrayAdapter;
importandroid.widget.Button;
importandroid.widget.EditText;
importandroid.widget.ExpandableListView;
importandroid.widget.ExpandableListView.OnChildClickListener;
importandroid.widget.ExpandableListView.OnGroupClickListener;
importandroid.widget.Spinner;
importandroid.widget.Toast;
publicclassMainActivity extendsActivity implementsOnClickListener{
privateLinkedHashMap<String, HeaderInfo> myDepartments= newLinkedHashMap<String, HeaderInfo>();
privateArrayList<HeaderInfo> deptList= newArrayList<HeaderInfo>();
privateMyListAdapter listAdapter;
privateExpandableListView myList;
@Override
publicvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner spinner = (Spinner) findViewById(R.id.department);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.dept_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
//Just add some data to start with
loadData();
//get reference to the ExpandableListView
myList = (ExpandableListView) findViewById(R.id.myList);
//create the adapter by passing your ArrayList data
listAdapter= newMyListAdapter(MainActivity.this,deptList);
//attach the adapter to the list
myList.setAdapter(listAdapter);
//expand all Groups
expandAll();
//add new item to the List
Button add = (Button) findViewById(R.id.add);
add.setOnClickListener(this);
//listener for child row click
myList.setOnChildClickListener(myListItemClicked);
//listener for group heading click
myList.setOnGroupClickListener(myListGroupClicked);
}
publicvoidonClick(View v) {
switch(v.getId()) {
//add entry to the List
caseR.id.add:
Spinner spinner = (Spinner) findViewById(R.id.department);
String department = spinner.getSelectedItem().toString();
EditText editText = (EditText) findViewById(R.id.product);
String product = editText.getText().toString();
editText.setText("");
//add a new item to the list
intgroupPosition = addProduct(department,product);
//notify the list so that changes can take effect
listAdapter.notifyDataSetChanged();
//collapse all groups
collapseAll();
//expand the group where item was just added
myList.expandGroup(groupPosition);
//set the current group to be selected so that it becomes visible
myList.setSelectedGroup(groupPosition);
break;
// More buttons go here (if any) ...
}
}
//method to expand all groups
privatevoidexpandAll() {
intcount = listAdapter.getGroupCount();
for(inti = 0; i < count; i++){
myList.expandGroup(i);
}
}
//method to collapse all groups
privatevoidcollapseAll() {
intcount = listAdapter.getGroupCount();
for(inti = 0; i < count; i++){
myList.collapseGroup(i);
}
}
//load some initial data into out list
privatevoidloadData(){
addProduct("Apparel","Activewear");
addProduct("Apparel","Jackets");
addProduct("Apparel","Shorts");
addProduct("Beauty","Fragrances");
addProduct("Beauty","Makeup");
}
//our child listener
privateOnChildClickListener myListItemClicked= newOnChildClickListener() {
publicbooleanonChildClick(ExpandableListView parent, View v,
intgroupPosition, intchildPosition, longid) {
//get the group header
HeaderInfo headerInfo = deptList.get(groupPosition);
//get the child info
DetailInfo detailInfo = headerInfo.getProductList().get(childPosition);
//display it or do something with it
Toast.makeText(getBaseContext(),"Clicked on Detail "+ headerInfo.getName()
+ "/"+ detailInfo.getName(), Toast.LENGTH_LONG).show();
returnfalse;
}
};
//our group listener
privateOnGroupClickListener myListGroupClicked= newOnGroupClickListener() {
publicbooleanonGroupClick(ExpandableListView parent, View v,
intgroupPosition, longid) {
//get the group header
HeaderInfo headerInfo = deptList.get(groupPosition);
//display it or do something with it
Toast.makeText(getBaseContext(),"Child on Header "+ headerInfo.getName(),
Toast.LENGTH_LONG).show();
returnfalse;
}
};
//here we maintain our products in various departments
privateintaddProduct(String department, String product){
intgroupPosition = 0;
//check the hash map if the group already exists
HeaderInfo headerInfo = myDepartments.get(department);
//add the group if doesn't exists
if(headerInfo == null){
headerInfo = newHeaderInfo();
headerInfo.setName(department);
myDepartments.put(department, headerInfo);
deptList.add(headerInfo);
}
//get the children for the group
ArrayList<DetailInfo> productList = headerInfo.getProductList();
//size of the children list
intlistSize = productList.size();
//add to the counter
listSize++;
//create a new child and add that to the group
DetailInfo detailInfo = newDetailInfo();
detailInfo.setSequence(String.valueOf(listSize));
detailInfo.setName(product);
productList.add(detailInfo);
headerInfo.setProductList(productList);
//find the group position inside the list
groupPosition = deptList.indexOf(headerInfo);
returngroupPosition;
}
}
MyListAdapter.java
importjava.util.ArrayList;
importandroid.content.Context;
importandroid.view.LayoutInflater;
importandroid.view.View;
importandroid.view.ViewGroup;
importandroid.widget.BaseExpandableListAdapter;
importandroid.widget.TextView;
publicclassMyListAdapter extendsBaseExpandableListAdapter {
privateContext context;
privateArrayList<HeaderInfo> deptList;
publicMyListAdapter(Context context, ArrayList<HeaderInfo> deptList) {
this.context= context;
this.deptList= deptList;
}
@Override
publicObject getChild(intgroupPosition, intchildPosition) {
ArrayList<DetailInfo> productList = deptList.get(groupPosition).getProductList();
returnproductList.get(childPosition);
}
@Override
publiclonggetChildId(intgroupPosition, intchildPosition) {
returnchildPosition;
}
@Override
publicView getChildView(intgroupPosition, intchildPosition, booleanisLastChild,
View view, ViewGroup parent) {
DetailInfo detailInfo = (DetailInfo) getChild(groupPosition, childPosition);
if(view == null) {
LayoutInflater infalInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = infalInflater.inflate(R.layout.child_row,null);
}
TextView sequence = (TextView) view.findViewById(R.id.sequence);
sequence.setText(detailInfo.getSequence().trim() + ") ");
TextView childItem = (TextView) view.findViewById(R.id.childItem);
childItem.setText(detailInfo.getName().trim());
returnview;
}
@Override
publicintgetChildrenCount(intgroupPosition) {
ArrayList<DetailInfo> productList = deptList.get(groupPosition).getProductList();
returnproductList.size();
}
@Override
publicObject getGroup(intgroupPosition) {
returndeptList.get(groupPosition);
}
@Override
publicintgetGroupCount() {
returndeptList.size();
}
@Override
publiclonggetGroupId(intgroupPosition) {
returngroupPosition;
}
@Override
publicView getGroupView(intgroupPosition, booleanisLastChild, View view,
ViewGroup parent) {
HeaderInfo headerInfo = (HeaderInfo) getGroup(groupPosition);
if(view == null) {
LayoutInflater inf = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inf.inflate(R.layout.group_heading,null);
}
TextView heading = (TextView) view.findViewById(R.id.heading);
heading.setText(headerInfo.getName().trim());
returnview;
}
@Override
publicbooleanhasStableIds() {
returntrue;
}
@Override
publicbooleanisChildSelectable(intgroupPosition, intchildPosition) {
returntrue;
}
}
HeaderInfo.java
importjava.util.ArrayList;
publicclassHeaderInfo {
privateString name;
privateArrayList<DetailInfo> productList= newArrayList<DetailInfo>();;
publicString getName() {
returnname;
}
publicvoidsetName(String name) {
this.name= name;
}
publicArrayList<DetailInfo> getProductList() {
returnproductList;
}
publicvoidsetProductList(ArrayList<DetailInfo> productList) {
this.productList= productList;
}
}
DetailInfo.java
publicclassDetailInfo {
privateString sequence= "";
privateString name= "";
publicString getSequence() {
returnsequence;
}
publicvoidsetSequence(String sequence) {
this.sequence= sequence;
}
publicString getName() {
returnname;
}
publicvoidsetName(String name) {
this.name= name;
}
}
activity_main.xml
<?xmlversion="1.0"encoding="UTF-8"?>
<RelativeLayoutxmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"android:layout_height="match_parent"
android:orientation="vertical">
<Spinnerandroid:id="@+id/department"android:layout_width="match_parent"
android:layout_height="wrap_content"android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"android:textStyle="bold"/>
<Buttonandroid:id="@+id/add"android:layout_width="wrap_content"
android:layout_height="wrap_content"android:layout_alignParentRight="true"
android:layout_below="@id/department"android:text="add"/>
<EditTextandroid:id="@+id/product"android:layout_width="fill_parent"
android:layout_height="wrap_content"android:layout_alignBaseline="@id/add"
android:layout_alignParentLeft="true"android:layout_below="@id/department"
android:layout_toLeftOf="@id/add"android:ems="10"android:hint="product_hint"
android:inputType="text"/>
<TextViewandroid:id="@+id/textView1"android:layout_width="match_parent"
android:layout_height="wrap_content"android:layout_alignParentLeft="true"
android:layout_below="@id/product"android:layout_margin="5dp"
android:padding="5dp"
android:text="department_store"android:textAppearance="? android:attr/textAppearanceMedium"
android:textStyle="bold"/>
<ExpandableListViewandroid:id="@+id/myList"
android:layout_width="match_parent"android:layout_height="fill_parent"
android:layout_below="@id/textView1"/>
</RelativeLayout>
child_row.xml
<?xmlversion="1.0"encoding="utf-8"?>
<RelativeLayoutandroid:layout_width="match_parent"android:layout_height="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>
group_heading.xml
<?xmlversion="1.0"encoding="utf-8"?>
<LinearLayoutxmlns: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>
dimens.xml
<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimenname="activity_horizontal_margin">16dp</dimen>
<dimenname="activity_vertical_margin">16dp</dimen>
</resources>
strings.xml
<?xmlversion="1.0"encoding="utf-8"?>
<resources>
<stringname="app_name">ExpandableListView</string>
<stringname="action_settings">Settings</string>
<stringname="hello_world">Hello world!</string>
<stringname="add">Add</string>
<stringname="menu_settings">Settings</string>
<stringname="title_activity_main">MainActivity</string>
<stringname="product_hint">Enter Products for the Store</string>
<stringname="department_store">My Department Store &#8230;</string>
<string-arrayname="dept_array">
<item>Apparel</item>
<item>Beauty</item>
<item>Electronics</item>
<item>Grocery</item>
<item>Home Improvement</item>
<item>Jewelry</item>
<item>Pharmacy</item>
</string-array>
<colorname="snow">#eee9e9</color>
</resources>
AndroidManifest.xml
<?xmlversion="1.0"encoding="utf-8"?>
<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.expandablelistview"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name="com.example.expandablelistview.MainActivity"
android:label="@string/app_name">
<intent-filter>
<actionandroid:name="android.intent.action.MAIN"/>
<categoryandroid:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>

Comments

Popular posts from this blog

Bitmap scalling and cropping from center

How to Bitmap scalling and cropping from center? public class ScalingUtilities {     /**      * Utility function for decoding an image resource. The decoded bitmap will      * be optimized for further scaling to the requested destination dimensions      * and scaling logic.      *      * @param res      *            The resources object containing the image data      * @param resId      *            The resource id of the image data      * @param dstWidth      *            Width of destination area      * @param dstHeight      *     ...

Custom camera using SurfaceView android with autofocus & auto lights & more

Custom camera using SurfaceView android with autofocus & auto lights & much more /**  * @author Tatyabhau Chavan  *  */ public class Preview extends SurfaceView implements SurfaceHolder.Callback {     private SurfaceHolder mHolder;     private Camera mCamera;     public Camera.Parameters mParameters;     private byte[] mBuffer;     private Activity mActivity;     // this constructor used when requested as an XML resource     public Preview(Context context, AttributeSet attrs) {         super(context, attrs);         init();     }     public Preview(Context context) {         super(context);         init();     }     public Camera getCamera() {        ...

Recycle view adapter in android

Recycle view adapter             The   RecyclerView   widget is a more advanced and flexible version of   ListView . This widget is a container for displaying large data sets that can be scrolled very efficiently by maintaining a limited number of views. Use the   RecyclerView widget when you have data collections whose elements change at runtime based on user action or network events. The   RecyclerView   class simplifies the display and handling of large data sets by providing: ·          Layout managers for positioning items ·          Default animations for common item operations, such as removal or addition of items You also have the flexibility to define custom layout managers and animations for   RecyclerView   widgets. RecyclerViewFragment.class public class RecyclerViewFragment...