I want to add one more level of in ExpandableListView.In current ExpandableListView is two level how can i add one more level. I am new in android developing please help me. Thanks in advance!
My MainActivity.java:-
private Toolbar mToolbar;
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
// private FragmentDrawer drawerFragment;
ArrayList<String> arraylist1,arraylist2,arraylist3,arrayList4,arrayList5;
int cnt = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
expListView = (ExpandableListView) findViewById(R.id.lvExp);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
/* drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);*/
// display the first navigation drawer view on app launch
// displayView(0);
Log.d("oncreate method", "");
arraylist1 = new ArrayList<String>();
arraylist2 = new ArrayList<String>();
arraylist3 = new ArrayList<String>();
arrayList4 = new ArrayList<String>();
arrayList5 = new ArrayList<String>();
new ProductsAsynTask().execute("http://opencart.codeniques.com/shopping/?route=feed/web_api/menu&key=test123$");
}
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding child data
listDataHeader.add("Top 250");
listDataHeader.add("Now Showing");
listDataHeader.add("Coming Soon..");
// Adding child data
List<String> top250 = new ArrayList<String>();
top250.add("The Shawshank Redemption");
top250.add("The Godfather");
top250.add("The Godfather: Part II");
top250.add("Pulp Fiction");
top250.add("The Good, the Bad and the Ugly");
top250.add("The Dark Knight");
top250.add("12 Angry Men");
List<String> nowShowing = new ArrayList<String>();
nowShowing.add("The Conjuring");
nowShowing.add("Despicable Me 2");
nowShowing.add("Turbo");
nowShowing.add("Grown Ups 2");
nowShowing.add("Red 2");
nowShowing.add("The Wolverine");
List<String> comingSoon = new ArrayList<String>();
comingSoon.add("2 Guns");
comingSoon.add("The Smurfs 2");
comingSoon.add("The Spectacular Now");
comingSoon.add("The Canyons");
comingSoon.add("Europa Report");
listDataChild.put(listDataHeader.get(0), top250); // Header, Child data
listDataChild.put(listDataHeader.get(1), nowShowing);
listDataChild.put(listDataHeader.get(2), comingSoon);
}
public class ProductsAsynTask extends AsyncTask<String,Void,Void>{
ProgressDialog dialog;
protected void onPreExecute(){
super.onPreExecute();
Log.d("In onPreExceute","");
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, Please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
protected Void doInBackground(String... param){
try{
Log.d("In doInBackground","");
HttpClient client= new DefaultHttpClient();
HttpPost post = new HttpPost(param[0]);
HttpResponse response = client.execute(post);
int status = response.getStatusLine().getStatusCode();
if(status == 200){
Log.d("Status",""+status);
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsonObject = new JSONObject(data);
JSONArray jArray = jsonObject.getJSONArray("categories");
for(int i = 0;i < jArray.length();i++){
cnt++;
Log.d("value of array",jArray.length()+"");
Log.d("Value of i",""+i);
JSONObject jsonObject1 = jArray.getJSONObject(i);
arraylist1.add(jsonObject1.getString("name"));
//data1 = jsonObject1.getString("name");
// Log.d("hello ",data1);
JSONArray jsonArray = jsonObject1.getJSONArray("children");
// JSONObject jsonObject2 = jsonObject1.getJSONObject("children");
for(int j=0;j<jsonArray.length();j++){
JSONObject jsonObject2 = jsonArray.getJSONObject(j);
arraylist2.add(jsonObject2.getString("name"));
// data2 = jsonObject2.getString("name");
JSONArray jsonArray1 = jsonObject2.getJSONArray("children_lv3");
for(int k=0;k<jsonArray1.length();k++){
JSONObject jsonObject3 = jsonArray1.getJSONObject(k);
arraylist3.add(jsonObject3.getString("name"));
arrayList4.add(jsonObject3.getString("href"));
/* data3 = jsonObject3.getString("name");
data4 = jsonObject3.getString("href"); */
}
arrayList5.add(jsonObject2.getString("href"));
// data5 = jsonObject2.getString("href");
}
}
}
}catch(IOException e){
Log.e("Error IOException :",e.getMessage());
}catch (JSONException e){
Log.e("Error JSONException",e.getMessage());
}
return null;
}
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
dialog.dismiss();
Log.d("Counter value",""+cnt);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if(id == R.id.action_search){
Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
/* public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new HomeFragment();
title = getString(R.string.title_home);
break;
case 1:
fragment = new FriendsFragment();
title = getString(R.string.title_friends);
break;
case 2:
fragment = new MessagesFragment();
title = getString(R.string.title_messages);
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
// set the toolbar title
getSupportActionBar().setTitle(title);
}
}*/}
My ExpandableListAdapter.java is here:-
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
public ExpandableListAdapter(Context context, List<String> listDataHeader,
HashMap<String, List<String>> listChildData) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
}
TextView txtListChild = (TextView) convertView
.findViewById(R.id.lblListItem);
txtListChild.setText(childText);
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}}
My activity_main.xml is here:-
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/container_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
</LinearLayout>
<FrameLayout
android:id="#+id/container_body"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
<ExpandableListView
android:id="#+id/lvExp"
android:layout_height="match_parent"
android:layout_width="260dp"
android:layout_gravity="start"/>
<!-- <fragment
android:id="#+id/fragment_navigation_drawer"
android:name="com.android.ShoppingMazza.activity.ExpandableListAdapter"
android:layout_width="#dimen/nav_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_navigation_drawer"
tools:layout="#layout/fragment_navigation_drawer" /> -->
</android.support.v4.widget.DrawerLayout>
You can try my following sample code. I have posted my full project to GitHub
Of course, you should modify more to meet all your requirements. For basic case, I only use the data source in the arrays.xml file. Hope this helps!
arrays.xml:
<resources>
<string-array name="items_array_expandable_level_one">
<item>Level 1.1</item>
<item>Level 1.2</item>
<item>Level 1.3</item>
</string-array>
<string-array name="items_array_expandable_level_one_one_child">
<item>Level 1.1.1</item>
<item>Level 1.1.2</item>
</string-array>
<string-array name="items_array_expandable_level_one_two_child">
<item>Level 1.2.1</item>
</string-array>
<string-array name="items_array_expandable_other_child">
<item>Second Level 01</item>
<item>Second Level 02</item>
<item>Second Level 03</item>
</string-array>
<string-array name="items_array_expandable_level_three">
<item>Child Level 01</item>
<item>Child Level 02</item>
</string-array>
</resources>
CustomExpListView.java:
public class CustomExpListView extends ExpandableListView
{
public CustomExpListView(Context context)
{
super(context);
}
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
widthMeasureSpec = MeasureSpec.makeMeasureSpec(960, MeasureSpec.AT_MOST);
heightMeasureSpec = MeasureSpec.makeMeasureSpec(600, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
ParentLevelAdapter.java:
public class ParentLevelAdapter extends BaseExpandableListAdapter {
private final Context mContext;
private final List<String> mListDataHeader;
private final Map<String, List<String>> mListData_SecondLevel_Map;
private final Map<String, List<String>> mListData_ThirdLevel_Map;
public ParentLevelAdapter(Context mContext, List<String> mListDataHeader) {
this.mContext = mContext;
this.mListDataHeader = new ArrayList<>();
this.mListDataHeader.addAll(mListDataHeader);
// Init second level data
String[] mItemHeaders;
mListData_SecondLevel_Map = new HashMap<>();
int parentCount = mListDataHeader.size();
for (int i = 0; i < parentCount; i++) {
String content = mListDataHeader.get(i);
switch (content) {
case "Level 1.1":
mItemHeaders = mContext.getResources().getStringArray(R.array.items_array_expandable_level_one_one_child);
break;
case "Level 1.2":
mItemHeaders = mContext.getResources().getStringArray(R.array.items_array_expandable_level_one_two_child);
break;
default:
mItemHeaders = mContext.getResources().getStringArray(R.array.items_array_expandable_other_child);
}
mListData_SecondLevel_Map.put(mListDataHeader.get(i), Arrays.asList(mItemHeaders));
}
// THIRD LEVEL
String[] mItemChildOfChild;
List<String> listChild;
mListData_ThirdLevel_Map = new HashMap<>();
for (Object o : mListData_SecondLevel_Map.entrySet()) {
Map.Entry entry = (Map.Entry) o;
Object object = entry.getValue();
if (object instanceof List) {
List<String> stringList = new ArrayList<>();
Collections.addAll(stringList, (String[]) ((List) object).toArray());
for (int i = 0; i < stringList.size(); i++) {
mItemChildOfChild = mContext.getResources().getStringArray(R.array.items_array_expandable_level_three);
listChild = Arrays.asList(mItemChildOfChild);
mListData_ThirdLevel_Map.put(stringList.get(i), listChild);
}
}
}
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final CustomExpListView secondLevelExpListView = new CustomExpListView(this.mContext);
String parentNode = (String) getGroup(groupPosition);
secondLevelExpListView.setAdapter(new SecondLevelAdapter(this.mContext, mListData_SecondLevel_Map.get(parentNode), mListData_ThirdLevel_Map));
secondLevelExpListView.setGroupIndicator(null);
return secondLevelExpListView;
}
#Override
public int getChildrenCount(int groupPosition) {
return 1;
}
#Override
public Object getGroup(int groupPosition) {
return this.mListDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this.mListDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.drawer_list_group, parent, false);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setTextColor(Color.CYAN);
lblListHeader.setText(headerTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
} }
SecondLevelAdapter.java:
public class SecondLevelAdapter extends BaseExpandableListAdapter
{
private final Context mContext;
private final List<String> mListDataHeader;
private final Map<String, List<String>> mListDataChild;
public SecondLevelAdapter(Context mContext, List<String> mListDataHeader, Map<String, List<String>> mListDataChild) {
this.mContext = mContext;
this.mListDataHeader = mListDataHeader;
this.mListDataChild = mListDataChild;
}
#Override
public Object getChild(int groupPosition, int childPosition)
{
return this.mListDataChild.get(this.mListDataHeader.get(groupPosition))
.get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition)
{
return childPosition;
}
#Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent)
{
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.drawer_list_item, parent, false);
}
TextView txtListChild = (TextView) convertView
.findViewById(R.id.lblListItem);
txtListChild.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
txtListChild.setText(childText);
return convertView;
}
#Override
public int getChildrenCount(int groupPosition)
{
try {
return this.mListDataChild.get(this.mListDataHeader.get(groupPosition)).size();
} catch (Exception e) {
return 0;
}
}
#Override
public Object getGroup(int groupPosition)
{
return this.mListDataHeader.get(groupPosition);
}
#Override
public int getGroupCount()
{
return this.mListDataHeader.size();
}
#Override
public long getGroupId(int groupPosition)
{
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent)
{
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.drawer_list_group_second, parent, false);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setText(headerTitle);
lblListHeader.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
lblListHeader.setTextColor(Color.YELLOW);
return convertView;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
MainActivity.java:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
// Init top level data
List<String> listDataHeader = new ArrayList<>();
String[] mItemHeaders = getResources().getStringArray(R.array.items_array_expandable_level_one);
Collections.addAll(listDataHeader, mItemHeaders);
ExpandableListView mExpandableListView = (ExpandableListView) findViewById(R.id.expandableListView_Parent);
if (mExpandableListView != null) {
ParentLevelAdapter parentLevelAdapter = new ParentLevelAdapter(this, listDataHeader);
mExpandableListView.setAdapter(parentLevelAdapter);
}
}
}
Screenshot result:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ExpandableListView
android:layout_width="fill_parent"
android:id="#+id/ParentLevel"
android:groupIndicator="#null"
android:layout_height="fill_parent">
</ExpandableListView>
</LinearLayout>
MainActivity.Java
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;
public class Home extends Activity
{
ExpandableListView explvlist;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
explvlist = (ExpandableListView)findViewById(R.id.ParentLevel);
explvlist.setAdapter(new ParentLevel());
}
public class ParentLevel extends BaseExpandableListAdapter
{
#Override
public Object getChild(int arg0, int arg1)
{
return arg1;
}
#Override
public long getChildId(int groupPosition, int childPosition)
{
return childPosition;
}
#Override
public View getChildView(int groupPosition, int childPosition,boolean isLastChild, View convertView, ViewGroup parent)
{
CustExpListview SecondLevelexplv = new CustExpListview(Home.this);
SecondLevelexplv.setAdapter(new SecondLevelAdapter());
SecondLevelexplv.setGroupIndicator(null);
return SecondLevelexplv;
}
#Override
public int getChildrenCount(int groupPosition)
{
return 3;
}
#Override
public Object getGroup(int groupPosition)
{
return groupPosition;
}
#Override
public int getGroupCount()
{
return 5;
}
#Override
public long getGroupId(int groupPosition)
{
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent)
{
TextView tv = new TextView(Home.this);
tv.setText("->FirstLevel");
tv.setBackgroundColor(Color.BLUE);
tv.setPadding(10, 7, 7, 7);
return tv;
}
#Override
public boolean hasStableIds()
{
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition)
{
return true;
}
}
public class CustExpListview extends ExpandableListView
{
int intGroupPosition, intChildPosition, intGroupid;
public CustExpListview(Context context)
{
super(context);
}
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
widthMeasureSpec = MeasureSpec.makeMeasureSpec(960, MeasureSpec.AT_MOST);
heightMeasureSpec = MeasureSpec.makeMeasureSpec(600, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public class SecondLevelAdapter extends BaseExpandableListAdapter
{
#Override
public Object getChild(int groupPosition, int childPosition)
{
return childPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition)
{
return childPosition;
}
#Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent)
{
TextView tv = new TextView(Home.this);
tv.setText("child");
tv.setPadding(15, 5, 5, 5);
tv.setBackgroundColor(Color.YELLOW);
tv.setLayoutParams(new ListView.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
return tv;
}
#Override
public int getChildrenCount(int groupPosition)
{
return 5;
}
#Override
public Object getGroup(int groupPosition)
{
return groupPosition;
}
#Override
public int getGroupCount()
{
return 1;
}
#Override
public long getGroupId(int groupPosition)
{
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,View convertView, ViewGroup parent)
{
TextView tv = new TextView(Home.this);
tv.setText("-->Second Level");
tv.setPadding(12, 7, 7, 7);
tv.setBackgroundColor(Color.RED);
return tv;
}
#Override
public boolean hasStableIds()
{
// TODO Auto-generated method stub
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition)
{
// TODO Auto-generated method stub
return true;
}
}
}
In this case you should create your own Expandable class.
Refer this link.
http://androidcodesnips.blogspot.in/2011/09/three-level-expandable-list.html
Create one more expandable list adapter extending BaseExpandableListAdapter, and in your ExpandableListAdapter getChildView(), call the new expandable list adapter.
I have implemented the same using following link:
https://github.com/talhahasanzia/Three-Level-Expandable-Listview
Related
I have an ExpandableListView of items and on list item I have TextView with two buttons to increment or decrements the value in TextView on clicks. The problem occurs every time I try to scroll the list. If I increment one item and then scroll the list the values get mixed (becouse the ListView keeps recycling its views) and I don't know how to fix it.
I have tried many soulutions I have found here, so yes this may be a duplicate, but I wasn't able to solve my problem with any method I have found.
My ExpandableListAdapter.java
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.TextView;
import java.util.HashMap;
import java.util.List;
public class ExpandableListAdapter extends BaseExpandableListAdapter {
public static class ViewHolder {
TextView childText;
TextView counterText;
Button addItemButton;
Button deleteItemButton;
int quantity = 0;
}
private Context context;
private List<String> listDataHeader;
private HashMap<String, List<String>> listHashMap;
public ExpandableListAdapter(Context context, List<String> listDataHeader, HashMap<String, List<String>> listHashMap) {
this.context = context;
this.listDataHeader = listDataHeader;
this.listHashMap = listHashMap;
}
#Override
public int getGroupCount() {
return listDataHeader.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return listHashMap.get(listDataHeader.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition) {
return listDataHeader.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return listHashMap.get(listDataHeader.get(groupPosition)).get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_group, null);
}
TextView listHeader = (TextView) convertView.findViewById(R.id.list_header);
listHeader.setTypeface(null, Typeface.BOLD);
listHeader.setText(headerTitle);
return convertView;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item, null);
TextView textListChild = (TextView) convertView.findViewById(R.id.list_item_header);
TextView itemsCounter = (TextView) convertView.findViewById(R.id.items_counter);
Button addItemButton = (Button) convertView.findViewById(R.id.plus_btn);
viewHolder = new ViewHolder();
viewHolder.childText = textListChild;
viewHolder.counterText = itemsCounter;
viewHolder.addItemButton = addItemButton;
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
final String childText = (String) getChild(groupPosition, childPosition);
viewHolder.childText.setText(childText);
viewHolder.addItemButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//int itemCount = Integer.parseInt((String)viewHolder.counterText.getText());
//itemCount++;
viewHolder.quantity++;
viewHolder.counterText.setText( Integer.toString(viewHolder.quantity));
PutOrderDrinks.addOrder(childText);
}
});
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
It is not a good idea to store quantity in ViewHolder.
Hope below sample helps :)
MainActivity.java:
public class MainActivity extends Activity {
Button clearChecks, putOrder;
ExpandableListView expandableListView;
ExpandableListViewAdapter expandableListAdapter;
int lastExpandedPosition = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
expandableListView = findViewById(R.id.expandedListView);
clearChecks = findViewById(R.id.btnClearChecks);
putOrder = findViewById(R.id.btnPutOrder);
List<String> listTitle = genGroupList();
expandableListAdapter = new ExpandableListViewAdapter(this, listTitle, genChildList(listTitle));
expandableListView.setAdapter(expandableListAdapter);
expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
if(lastExpandedPosition != -1 && (lastExpandedPosition != groupPosition)){
expandableListView.collapseGroup(lastExpandedPosition);
}
lastExpandedPosition = groupPosition;
}
});
clearChecks.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
expandableListAdapter.clearChecks();
}
});
putOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ArrayList<ChildItemSample> putOrder = expandableListAdapter.getOrderList();
String msg = "";
for(int i=0; i<putOrder.size(); i++){
msg += putOrder.get(i).getName() + ": " + putOrder.get(i).getQty() + "\n";
}
Toast.makeText(getBaseContext(), msg, Toast.LENGTH_LONG).show();
}
});
}
private ArrayList<String> genGroupList(){
ArrayList<String> listGroup = new ArrayList<>();
for(int i=1; i<10; i++){
listGroup.add("Group: " + i);
}
return listGroup;
}
private Map<String, List<ChildItemSample>> genChildList(List<String> header){
Map<String, List<ChildItemSample>> listChild = new HashMap<>();
for(int i=0; i<header.size(); i++){
List<ChildItemSample> testDataList = new ArrayList<>();
int a = (int)(Math.random()*8);
for(int j=0; j<a; j++){
ChildItemSample testItem = new ChildItemSample("Child " + (j + 1), 0);
testDataList.add(testItem);
}
listChild.put(header.get(i), testDataList);
}
return listChild;
}
}
ChildItemSample.java:
public class ChildItemSample {
private boolean checked = false;
private String name;
private int qty;
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public String getName() {
return name;
}
public ChildItemSample(String name, int qty){
this.name = name;
this.qty = qty;
}
}
ExpandableListViewAdapter.java:
public class ExpandableListViewAdapter extends BaseExpandableListAdapter {
private Context context;
private List<String> listGroup;
private Map<String, List<ChildItemSample>> listChild;
private int checkedBoxesCount;
private boolean[] checkedGroup;
public ExpandableListViewAdapter(Context context, List<String> listGroup, Map<String,
List<ChildItemSample>> listChild) {
this.context = context;
this.listGroup = listGroup;
this.listChild = listChild;
checkedBoxesCount = 0;
checkedGroup = new boolean[listGroup.size()];
}
#Override
public int getGroupCount() {
return listGroup.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return listChild.get(listGroup.get(groupPosition)).size();
}
#Override
public String getGroup(int groupPosition) {
return listGroup.get(groupPosition);
}
#Override
public ChildItemSample getChild(int groupPosition, int childPosition) {
return listChild.get(listGroup.get(groupPosition)).get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean b, View view, ViewGroup viewGroup) {
String itemGroup = getGroup(groupPosition);
GroupViewHolder groupViewHolder;
if(view == null){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.expanded_list_group, null);
groupViewHolder = new GroupViewHolder();
groupViewHolder.tvGroup = view.findViewById(R.id.tv_group);
groupViewHolder.cbGroup = view.findViewById(R.id.cb_group);
groupViewHolder.cbGroup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int pos = (int)view.getTag();
checkedGroup[pos] = !checkedGroup[pos];
for(ChildItemSample item : listChild.get(listGroup.get(pos))){
item.setChecked(checkedGroup[pos]);
}
notifyDataSetChanged();
}
});
view.setTag(groupViewHolder);
}else {
groupViewHolder = (GroupViewHolder)view.getTag();
}
groupViewHolder.tvGroup.setText(String.format("%s (%d)", itemGroup, getChildrenCount(groupPosition)));
if(checkedGroup[groupPosition]) groupViewHolder.cbGroup.setChecked(true);
else groupViewHolder.cbGroup.setChecked(false);
groupViewHolder.cbGroup.setTag(groupPosition);
return view;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean b, View view, ViewGroup viewGroup) {
ChildItemSample expandedListText = getChild(groupPosition,childPosition);
ChildViewHolder childViewHolder;
if(view == null){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.expanded_list_item, null);
childViewHolder = new ChildViewHolder();
childViewHolder.tvChild = view.findViewById(R.id.tv_child);
childViewHolder.cbChild = view.findViewById(R.id.cb_child);
childViewHolder.tvQty = view.findViewById(R.id.tv_qty);
childViewHolder.btInc = view.findViewById(R.id.bt_inc);
childViewHolder.btDec = view.findViewById(R.id.bt_dec);
childViewHolder.cbChild.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CheckBox cb = (CheckBox) view;
Pos pos = (Pos) cb.getTag();
ChildItemSample selectedItem = getChild(pos.group, pos.child);
selectedItem.setChecked(cb.isChecked());
if(cb.isChecked()){
checkedBoxesCount++;
Toast.makeText(context,"Checked value is: " + getChild(pos.group, pos.child).getName(),
Toast.LENGTH_SHORT).show();
}else {
checkedBoxesCount--;
if(checkedBoxesCount == 0){
Toast.makeText(context,"nothing checked",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(context,"unchecked",Toast.LENGTH_SHORT).show();
}
}
notifyDataSetChanged();
}
});
childViewHolder.btInc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Button bt = (Button) view;
Pos pos = (Pos) bt.getTag();
ChildItemSample selectedItem = getChild(pos.group, pos.child);
selectedItem.setQty(selectedItem.getQty() + 1);
notifyDataSetChanged();
}
});
childViewHolder.btDec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Button bt = (Button) view;
Pos pos = (Pos) bt.getTag();
ChildItemSample selectedItem = getChild(pos.group, pos.child);
if(selectedItem.getQty() > 0) selectedItem.setQty(selectedItem.getQty() - 1);
notifyDataSetChanged();
}
});
}else {
childViewHolder = (ChildViewHolder)view.getTag();
}
childViewHolder.cbChild.setChecked(expandedListText.isChecked());
childViewHolder.tvChild.setText(expandedListText.getName() + " :");
childViewHolder.tvQty.setText("" + expandedListText.getQty());
childViewHolder.cbChild.setTag(new Pos(groupPosition, childPosition));
childViewHolder.btInc.setTag(new Pos(groupPosition, childPosition));
childViewHolder.btDec.setTag(new Pos(groupPosition, childPosition));
view.setTag(childViewHolder);
return view;
}
public void clearChecks() {
for(int i=0; i<checkedGroup.length; i++) checkedGroup[i] = false;
for(List<ChildItemSample> value : listChild.values()) {
for (ChildItemSample sample : value) {
sample.setChecked(false);
}
}
checkedBoxesCount = 0;
notifyDataSetChanged();
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
private class GroupViewHolder {
CheckBox cbGroup;
TextView tvGroup;
}
private class ChildViewHolder {
CheckBox cbChild;
TextView tvChild;
TextView tvQty;
Button btInc;
Button btDec;
}
private class Pos {
int group;
int child;
Pos(int group, int child){
this.group = group;
this.child = child;
}
}
public ArrayList<ChildItemSample> getOrderList(){
ArrayList<ChildItemSample> overallOrder = new ArrayList<>();
for(int i=0; i<getGroupCount(); i++){
for(int j=0; j<getChildrenCount(i); j++){
if(getChild(i,j).getQty() > 0){
ChildItemSample newOrder = new ChildItemSample(getGroup(i) + ">" +
getChild(i, j).getName(), getChild(i, j).getQty());
overallOrder.add(newOrder);
}
}
}
return overallOrder;
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/btnClearChecks"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Clear Checks" />
<Button
android:id="#+id/btnPutOrder"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Put Order" />
</LinearLayout>
<ExpandableListView
android:id="#+id/expandedListView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ExpandableListView>
</LinearLayout>
expanded_list_group.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants" >
<CheckBox
android:id="#+id/cb_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:layout_gravity="center_vertical" />
<TextView
android:id="#+id/tv_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text"
android:textSize="30sp" />
</LinearLayout>
expanded_list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<CheckBox
android:id="#+id/cb_child"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_marginLeft="60dp" />
<TextView
android:id="#+id/tv_child"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/cb_child"
android:text="Child: "
android:textSize="20sp" />
<TextView
android:id="#+id/tv_qty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/tv_child"
android:text="0"
android:textSize="20sp" />
<Button
android:id="#+id/bt_inc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/bt_dec"
android:text="+" />
<Button
android:id="#+id/bt_dec"
android:layout_marginRight="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:text="-" />
</RelativeLayout>
Try this adapter:
public class ExpandableListAdapter extends BaseExpandableListAdapter {
class ViewHolder {
TextView childText;
TextView counterText;
Button addItemButton;
Button deleteItemButton;
}
class ChildItem{
String name;
int quantity;
ChildItem(String name, int quantity){
this.name = name;
this.quantity = quantity;
}
}
class Pos{
int group;
int child;
Pos(int group, int child){
this.group = group;
this.child = child;
}
}
private Context context;
private List<String> listDataHeader;
//private HashMap<String, List<String>> listHashMap;
private HashMap<String, List<ChildItem>> listChildMap;
public ExpandableListAdapter(Context context, List<String> listDataHeader, HashMap<String, List<String>> listHashMap) {
this.context = context;
this.listDataHeader = listDataHeader;
listChildMap = new HashMap<>();
for(int i=0; i<getGroupCount(); i++){
List<ChildItem> listTemp = new ArrayList<>();
for(int j=0; j<listHashMap.get(listDataHeader.get(i)).size(); j++){
listTemp.add(new ChildItem(listHashMap.get(listDataHeader.get(i)).get(j), 0));
}
listChildMap.put(listDataHeader.get(i), listTemp);
}
}
#Override
public int getGroupCount() {
return listDataHeader.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return listChildMap.get(listDataHeader.get(groupPosition)).size();
}
#Override
public String getGroup(int groupPosition) {
return listDataHeader.get(groupPosition);
}
#Override
public ChildItem getChild(int groupPosition, int childPosition) {
return listChildMap.get(listDataHeader.get(groupPosition)).get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
String headerTitle = getGroup(groupPosition);
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_group, null);
}
TextView listHeader = (TextView) convertView.findViewById(R.id.list_header);
listHeader.setTypeface(null, Typeface.BOLD);
listHeader.setText(headerTitle);
return convertView;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item, null);
TextView textListChild = (TextView) convertView.findViewById(R.id.list_item_header);
TextView itemsCounter = (TextView) convertView.findViewById(R.id.items_counter);
Button addItemButton = (Button) convertView.findViewById(R.id.plus_btn);
viewHolder = new ViewHolder();
viewHolder.childText = textListChild;
viewHolder.counterText = itemsCounter;
viewHolder.addItemButton = addItemButton;
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
ChildItem child = getChild(groupPosition, childPosition);
viewHolder.childText.setText(child.name);
viewHolder.counterText.setText("" + child.quantity);
viewHolder.addItemButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Pos pos = (Pos)v.getTag();
ChildItem selectedItem = getChild(pos.group, pos.child);
selectedItem.quantity = selectedItem.quantity + 1;
notifyDataSetChanged();
PutOrderDrinks.addOrder(selectedItem.name);
}
});
viewHolder.addItemButton.setTag(new Pos(groupPosition, childPosition));
convertView.setTag(viewHolder);
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
I have an ExpandableListView which is populated using data coming from serverside(reftrofit) how can I use an Adapter to get a specific element of the object? The expandable list view contains parent and child elements. When I click on the child element I would like to extract an ID(SensorID) that is associated with that child element.
I Have an Adapterwhere I am attempting to extract the ID from the object but I am unable to. I noticed that for an array Adapterthe getItemAtPosition() method is used to get an index then extract an element from the object(sensorID).
I am however not sure if this is the same method that should be used for an ExpandableListAdapter because I have seen snippets of code where the method getChild() is used.
The error I get everytime on click reads
ExpandableListConnector cannot be cast to
com.xera.deviceinsight.home.ExpandableListAdapter
The method in question
private void load(View view)
{
expListView = (ExpandableListView) view.findViewById(R.id.lvExp);
prepareListData();
listAdapter = new ExpandableListAdapter(this.getActivity(), listDataHeader, listDataChild);
expListView.setAdapter(listAdapter);
expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
System.err.println("child clicked");
Toast.makeText(getActivity(), "child clicked", Toast.LENGTH_SHORT).show();
EventBus.getDefault().post(new ItemClickedEvent(SensorInformationChildFragment.TAB_CALL));
ExpandableListAdapter adapter = (ExpandableListAdapter)parent.getAdapter();
OrganisationDeviceSensorsResult deviceSensor = (OrganisationDeviceSensorsResult) adapter.getChild(groupPosition , childPosition);
sensorID = deviceSensor.SensorID;
ReportingGroup.get(childPosition);
return true;
}
});
}
Adapter:
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
public List<OrganisationDeviceSensorsResult> Items;
public ExpandableListAdapter(Context context, List<String> listDataHeader,
HashMap<String, List<String>> listChildData) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
public OrganisationDeviceSensorsResult getItemAtPosition(int index)
{
return getItemAtPosition(index);
//return this.getItem(index);
//return this.getItem(index);
//return index;
//return this.get
//return OrganisationDeviceSensorsResult.
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
OrganisationDeviceSensorsResult deviceSensor = getItemAtPosition(childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
}
TextView txtListChild = (TextView) convertView
.findViewById(R.id.lblListItem);
txtListChild.setText(childText);
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
I had more or less your situation, I do it with this code in the Activity where the listview is placed:
contactListExpandable = (ExpandableListView) findViewById(R.id.contactlist);
contactListAdapter = new ContactListAdapter(this, chatGroupList);
contactListExpandable.setAdapter(contactListAdapter);
contactListExpandable.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View view, int groupPosition, int childPosition, long id) {
ChatContact contact = chatGroupList.get(groupPosition).getContacts().get(childPosition);
launchChat(contact, null, false, "");
return false;
}
});
In my case, I get the child Object to launch a chat, etc, in your case you will be abre to obtain the Sensor object and do your stuff
=== ChatGroup ===
public class ChatGroup implements Comparable{
final public String name;
private List<ChatContact> contacts;
public ChatGroup(String name){
this.name = name;
this.contacts = new ArrayList<>();
}
public void addContact(ChatContact contact){
this.contacts.add(contact);
}
public List<ChatContact> getContacts(){
return this.contacts;
}
#Override
public int compareTo(Object o) {
ChatGroup cg = (ChatGroup)o;
return name.compareTo(cg.name);
}
}
=== ChatContact.java ===
public class ChatContact implements Parcelable, Comparable {
final public String name;
final public String jid;
public Status status;
public ChatContact(String name, String jid) {
this.name = name;
this.jid = jid;
}
.....getters/setters/etc.....
}
I want to show the count and all the data when clicked. But so far in testing using click on the Parent item
I tried increment checkedCount when check. But it show only checked count in in one group child elemements.
My Adapter:
public class RubExpandAdapter extends BaseExpandableListAdapter {
private Context context;
private List<RubricsModel> rubrics;
private List<VacancyModel> listForRubricListView;
private List<VacancyModel> listForSubRubricListView;
private HashMap<Integer, boolean[]> mChildCheckStates;
public static int rubricPage = 1;
public static int rubricId;
public static int subRubricPage = 1;
public static int subRubricId;
int checkedCount;
FragmentManager fm;
public RubExpandAdapter(Context context, ArrayList<RubricsModel> rubrics, FragmentManager fragmentManager) {
this.context = context;
this.rubrics = rubrics;
fm = fragmentManager;
listForRubricListView = new ArrayList<>();
mChildCheckStates = new HashMap<>();
}
#Override
public Object getChild(int groupPosition, int childPosition) {
ArrayList<SubRubricsModel> chList = rubrics.get(groupPosition)
.getItems();
return chList.get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final int mGroupPosition = groupPosition;
final int mChildPosition = childPosition;
SubRubricsModel subRubricsModel = (SubRubricsModel) getChild(groupPosition,
childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context
.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.rubrics_child_row_layout, null);
}
final CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
TextView tv = (TextView) convertView.findViewById(R.id.tvsubrubricsfr);
tv.setText(subRubricsModel.getSubRubricName());
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkBox.setChecked(!checkBox.isChecked());
}
});
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
boolean getChecked[] = mChildCheckStates.get(mGroupPosition);
getChecked[mChildPosition] = isChecked;
mChildCheckStates.put(mGroupPosition, getChecked);
} else {
boolean getChecked[] = mChildCheckStates.get(mGroupPosition);
getChecked[mChildPosition] = isChecked;
mChildCheckStates.put(mGroupPosition, getChecked);
}
for (int i = 0; i < mChildCheckStates.size(); i++){
if (mChildCheckStates.containsValue(true)){
checkedCount ++;
}
}
}
});
if (mChildCheckStates.containsKey(mGroupPosition)) {
boolean getChecked[] = mChildCheckStates.get(mGroupPosition);
checkBox.setChecked(getChecked[mChildPosition]);
} else {
boolean getChecked[] = new boolean[getChildrenCount(mGroupPosition)];
mChildCheckStates.put(mGroupPosition, getChecked);
checkBox.setChecked(false);
}
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
ArrayList<SubRubricsModel> chList = rubrics.get(groupPosition)
.getItems();
return chList.size();
}
#Override
public Object getGroup(int groupPosition) {
return rubrics.get(groupPosition);
}
#Override
public int getGroupCount() {
return rubrics.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
final RubricsModel rubricsModel = (RubricsModel) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater inf = (LayoutInflater) context
.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView = inf.inflate(R.layout.rubrics_group_row_layout, null);
}
TextView tv = (TextView) convertView.findViewById(R.id.tvrubricsfr);
tv.setText(rubricsModel.getRubricName());
ImageView indicator = (ImageView) convertView.findViewById(R.id.ivGroupIndicator);
if (isExpanded) {
indicator.setImageResource(R.drawable.arrow_down);
} else {
indicator.setImageResource(R.drawable.arrow_right);
}
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// RubFragment.searchByRubrics = true;
// rubricId = rubricsModel.getRubricID();
// searchByRubric(String.valueOf(rubricId));
Toast.makeText(context, String.valueOf(mChildCheckStates.size()), Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
}
how to do, tell me, pls?
I want to add different children into different child in ExpandableList.
My MainActivity.java:-
public class MainActivity extends AppCompatActivity {
//private static String TAG = MainActivity.class.getSimpleName();
private Toolbar mToolbar;
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
int arraylistvalue = 0;
ArrayList<String> arraylist1,arraylist2,arraylist3,arrayList4,arrayList5;
int cnt = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
arraylist1 = new ArrayList<String>();
arraylist2 = new ArrayList<String>();
arraylist3 = new ArrayList<String>();
arrayList4 = new ArrayList<String>();
arrayList5 = new ArrayList<String>();
new ProductsAsynTask().execute("http://opencart.codeniques.com/shopping/?route=feed/web_api/menu&key=test123$");
}
public class ProductsAsynTask extends AsyncTask<String,Void,Void>{
ProgressDialog dialog;
protected void onPreExecute(){
super.onPreExecute();
Log.d("In onPreExceute","");
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, Please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
protected Void doInBackground(String... param){
try{
Log.d("In doInBackground","");
HttpClient client= new DefaultHttpClient();
HttpPost post = new HttpPost(param[0]);
HttpResponse response = client.execute(post);
int status = response.getStatusLine().getStatusCode();
if(status == 200){
Log.d("Status",""+status);
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsonObject = new JSONObject(data);
JSONArray jArray = jsonObject.getJSONArray("categories");
for(int i = 0;i < jArray.length();i++){
cnt++;
Log.d("value of array",jArray.length()+"");
Log.d("Value of i",""+i);
JSONObject jsonObject1 = jArray.getJSONObject(i);
arraylist1.add(jsonObject1.getString("name"));
//data1 = jsonObject1.getString("name");
// Log.d("hello ",data1);
JSONArray jsonArray = jsonObject1.getJSONArray("children");
// JSONObject jsonObject2 = jsonObject1.getJSONObject("children");
for(int j=0;j<jsonArray.length();j++){
JSONObject jsonObject2 = jsonArray.getJSONObject(j);
arraylist2.add(jsonObject2.getString("name"));
// data2 = jsonObject2.getString("name");
JSONArray jsonArray1 = jsonObject2.getJSONArray("children_lv3");
for(int k=0;k<jsonArray1.length();k++){
JSONObject jsonObject3 = jsonArray1.getJSONObject(k);
arraylist3.add(jsonObject3.getString("name"));
arrayList4.add(jsonObject3.getString("href"));
/* data3 = jsonObject3.getString("name");
data4 = jsonObject3.getString("href"); */
}
arrayList5.add(jsonObject2.getString("href"));
// data5 = jsonObject2.getString("href");
}
}
}
}catch(IOException e){
Log.e("Error IOException :",e.getMessage());
}catch (JSONException e){
Log.e("Error JSONException",e.getMessage());
}
return null;
}
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
dialog.dismiss();
expListView = (ExpandableListView) findViewById(R.id.lvExp);
expListView.setAdapter(new ParentLevel());
Log.d("Counter value",""+cnt);
}
}
public class ParentLevel extends BaseExpandableListAdapter
{
#Override
public Object getChild(int arg0, int arg1)
{
return arg1;
}
#Override
public long getChildId(int groupPosition, int childPosition)
{
return childPosition;
}
#Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent)
{
CustExpListview SecondLevelexplv = new CustExpListview(MainActivity.this);
SecondLevelexplv.setAdapter(new SecondLevelAdapter());
SecondLevelexplv.setGroupIndicator(null);
return SecondLevelexplv;
}
#Override
public int getChildrenCount(int groupPosition)
{
return 3;
}
#Override
public Object getGroup(int groupPosition)
{
return groupPosition;
}
#Override
public int getGroupCount()
{
int columr = arraylist1.size();
return columr;
}
#Override
public long getGroupId(int groupPosition)
{
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent)
{
TextView tv = new TextView(MainActivity.this);
tv.setText("");
tv.setBackgroundColor(Color.BLUE);
tv.setPadding(10, 7, 7, 7);
return tv;
}
#Override
public boolean hasStableIds()
{
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition)
{
return true;
}
}
public class CustExpListview extends ExpandableListView
{
int intGroupPosition, intChildPosition, intGroupid;
public CustExpListview(Context context)
{
super(context);
}
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
widthMeasureSpec = MeasureSpec.makeMeasureSpec(960, MeasureSpec.AT_MOST);
heightMeasureSpec = MeasureSpec.makeMeasureSpec(600, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public class SecondLevelAdapter extends BaseExpandableListAdapter
{
#Override
public Object getChild(int groupPosition, int childPosition)
{
return childPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition)
{
return childPosition;
}
#Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent)
{
TextView tv = new TextView(MainActivity.this);
tv.setText("child");
tv.setPadding(15, 5, 5, 5);
tv.setBackgroundColor(Color.YELLOW);
tv.setLayoutParams(new ListView.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
return tv;
}
#Override
public int getChildrenCount(int groupPosition)
{
return 5;
}
#Override
public Object getGroup(int groupPosition)
{
return groupPosition;
}
#Override
public int getGroupCount()
{
return 1;
}
#Override
public long getGroupId(int groupPosition)
{
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent)
{
TextView tv = new TextView(MainActivity.this);
tv.setText("-->Second Level");
tv.setPadding(12, 7, 7, 7);
tv.setBackgroundColor(Color.RED);
return tv;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return true;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if(id == R.id.action_search){
Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
}
My activity.xml is here:-
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/container_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
</LinearLayout>
<FrameLayout
android:id="#+id/container_body"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
<ExpandableListView
android:id="#+id/lvExp"
android:layout_height="match_parent"
android:layout_width="260dp"
android:layout_gravity="start"/>
<!-- <fragment
android:id="#+id/fragment_navigation_drawer"
android:name="com.android.ShoppingMazza.activity.ExpandableListAdapter"
android:layout_width="#dimen/nav_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_navigation_drawer"
tools:layout="#layout/fragment_navigation_drawer" /> -->
</android.support.v4.widget.DrawerLayout>
I also want drawer below in toolbar.I am new in android developing Please help me Thanks in advance
activitymain.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ExpandableListView
android:layout_width="fill_parent"
android:id="#+id/ParentLevel"
android:groupIndicator="#null"
android:layout_height="fill_parent">
</ExpandableListView>
MainActivity.java
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;
public class Home extends Activity
{
ExpandableListView explvlist;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
explvlist = (ExpandableListView)findViewById(R.id.ParentLevel);
explvlist.setAdapter(new ParentLevel());
}
public class ParentLevel extends BaseExpandableListAdapter
{
#Override
public Object getChild(int arg0, int arg1)
{
return arg1;
}
#Override
public long getChildId(int groupPosition, int childPosition)
{
return childPosition;
}
#Override
public View getChildView(int groupPosition, int childPosition,boolean isLastChild, View convertView, ViewGroup parent)
{
CustExpListview SecondLevelexplv = new CustExpListview(Home.this);
SecondLevelexplv.setAdapter(new SecondLevelAdapter());
SecondLevelexplv.setGroupIndicator(null);
return SecondLevelexplv;
}
#Override
public int getChildrenCount(int groupPosition)
{
return 3;
}
#Override
public Object getGroup(int groupPosition)
{
return groupPosition;
}
#Override
public int getGroupCount()
{
return 5;
}
#Override
public long getGroupId(int groupPosition)
{
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent)
{
TextView tv = new TextView(Home.this);
tv.setText("->FirstLevel");
tv.setBackgroundColor(Color.BLUE);
tv.setPadding(10, 7, 7, 7);
return tv;
}
#Override
public boolean hasStableIds()
{
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition)
{
return true;
}
}
public class CustExpListview extends ExpandableListView
{
int intGroupPosition, intChildPosition, intGroupid;
public CustExpListview(Context context)
{
super(context);
}
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
widthMeasureSpec = MeasureSpec.makeMeasureSpec(960, MeasureSpec.AT_MOST);
heightMeasureSpec = MeasureSpec.makeMeasureSpec(600, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public class SecondLevelAdapter extends BaseExpandableListAdapter
{
#Override
public Object getChild(int groupPosition, int childPosition)
{
return childPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition)
{
return childPosition;
}
#Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent)
{
TextView tv = new TextView(Home.this);
tv.setText("child");
tv.setPadding(15, 5, 5, 5);
tv.setBackgroundColor(Color.YELLOW);
tv.setLayoutParams(new ListView.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
return tv;
}
#Override
public int getChildrenCount(int groupPosition)
{
return 5;
}
#Override
public Object getGroup(int groupPosition)
{
return groupPosition;
}
#Override
public int getGroupCount()
{
return 1;
}
#Override
public long getGroupId(int groupPosition)
{
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,View convertView, ViewGroup parent)
{
TextView tv = new TextView(Home.this);
tv.setText("-->Second Level");
tv.setPadding(12, 7, 7, 7);
tv.setBackgroundColor(Color.RED);
return tv;
}
#Override
public boolean hasStableIds()
{
// TODO Auto-generated method stub
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition)
{
// TODO Auto-generated method stub
return true;
}
}
}
My Fragment didn't show anything for my expandable view. there's not error as well. and i don't know where went wrong so i need help Can someone let me know my error? There's no error on the page/didn't have any crashes as well
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.HashMap;
import java.util.List;
public class MyExpandableListAdapter extends BaseExpandableListAdapter {
private Context context;
private List<String> listGroup;
private HashMap<String, List<String>> listChild;
public MyExpandableListAdapter(Context context, List<String> listGroup,
HashMap<String, List<String>> listChild) {
this.context = context;
this.listGroup = listGroup;
this.listChild = listChild;
}
#Override
public int getGroupCount() {
return listGroup.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return listChild.get(listGroup.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition) {
return listGroup.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return listChild.get(listGroup.get(groupPosition)).get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.group_layout, null);
}
String textGroup = (String) getGroup(groupPosition);
TextView textViewGroup = (TextView) convertView
.findViewById(R.id.group);
textViewGroup.setText(textGroup);
return convertView;
}
#Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.item_layout, null);
}
TextView textViewItem = (TextView) convertView.findViewById(R.id.item);
String text = (String) getChild(groupPosition, childPosition);
textViewItem.setText(text);
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return false;
}
}
public class Hotel extends Fragment {
ExpandableListView expandableListView;
MyExpandableListAdapter myExpandableListAdapter;
List<String> groupList;
HashMap<String, List<String>> childMap;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.hotel_frag, container, false);
init();
expandableListView = (ExpandableListView) v.findViewById(R.id.mylist);
expandableListView.setAdapter(myExpandableListAdapter);
myExpandableListAdapter = new MyExpandableListAdapter(Hotel.this.getActivity().getApplicationContext(), groupList, childMap);
return v;
}
private void init() {
groupList = new ArrayList<String>();
childMap = new HashMap<String, List<String>>();
List<String> groupList0 = new ArrayList<String>();
groupList0.add("groupList0 - 1");
groupList0.add("groupList0 - 2");
groupList0.add("groupList0 - 3");
List<String> groupList1 = new ArrayList<String>();
groupList1.add("groupList1 - 1");
groupList1.add("groupList1 - 2");
groupList1.add("groupList1 - 3");
List<String> groupList2 = new ArrayList<String>();
groupList2.add("groupList2 - 1");
groupList2.add("groupList2 - 2");
groupList2.add("groupList2 - 3");
List<String> groupList3 = new ArrayList<String>();
groupList3.add("groupList3 - 1");
groupList3.add("groupList3 - 2");
groupList3.add("groupList3 - 3");
groupList.add("Group List 0");
groupList.add("Group List 1");
groupList.add("Group List 2");
groupList.add("Group List 3");
childMap.put(groupList.get(0), groupList0);
childMap.put(groupList.get(1), groupList1);
childMap.put(groupList.get(2), groupList2);
childMap.put(groupList.get(3), groupList3);
}
}
http://i.stack.imgur.com/dnM7Q.png
http://i.stack.imgur.com/eXJOz.png
http://i.stack.imgur.com/VmaUj.png
You have to construct the adapter before you assign it to the ListView:
init();
myExpandableListAdapter = new MyExpandableListAdapter(Hotel.this.getActivity().getApplicationContext(), groupList, childMap);
expandableListView = (ExpandableListView) v.findViewById(R.id.mylist);
expandableListView.setAdapter(myExpandableListAdapter);