I have an expandableListView which contains a number of checkboxes inside. For my app, I would like to be able to save the check value of these checklists, however, I can't use sharedPreferences, as i Have to use a Hashmap which contains an array of booleans. This is my code
import java.util.HashMap;
import java.util.Map.Entry;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
public class ExpListAdapter extends BaseExpandableListAdapter {
private Context context;
//second attempt to hold the values
private SharedPreferences inventorylistcheckStateData;
private String[] parentList = { "Bedding", "Bedroom Items", "Clothing",
"Bags", "Stationary", "Documents", "Electronics", "Toiletries",
"Kitchen Items" };
// used to retain our checklist values, which for some reason dont stick.
private HashMap<Integer, boolean[]> checkState;
// multidimensional string storage is needed as you are storing values for
// two lists.
private String[][] childList = {
{ "Single/Double sheets", "Single/Double duvet + Covers",
"Pillows + Pillow cases" },
{ "Alarm Clock", "Posters", "Door Wedge", "Lamp", "Small Bin",
"Hamper Basket" },
{ "Casual Clothes, i.e T shirts, jeans, hoodies",
"Smart clothing for interviews and presentations",
"Warm Clothing (especially for newcastle)",
"'Party Clothes' clothes for going out",
"Underwear and socks", "pyjamas", "Comfortable shoes",
"Sports trainers", "Swimwear" },
{ "Everyday bag/backpack", "Gym bag", "Clear Pencil Case",
"Purse/Wallet", "Watch" },
{ "Pins", "A4 Notebooks", "Pens/Pencils", "Highlighters", "Ruler",
"Rubber", "Selotape", "Hole Puncher", "A4 Binders",
"Calculater", "Calender" },
{ "Passport photos", "Passport",
"Driving License (some form of id)", "Your NI Card",
"Insurance Documents", "NHS Medical Card",
"Insurance documents", "Letter of Acceptance",
"Scholarship/bursury letters",
"Rail Card(if you have one)", "C.V" },
{ "Laptop+Charger", "Mouse", "Phone + Charger", "Ethernet Cables",
"USB memory stick", "Headphones", "Digital Camera",
"MP3 Player" },
{ "Shampoo", "Razors", "Toothbrush and toothpaste",
"Make-up/remover", "HairBrush",
"Condoms or other protection!!!" },
{ "Frying Pan", "Wok", "Tin Opener", "Bottle opener", "Glasses",
"Cheese Grater", "Knives", "Chopping Board", "Scissors",
"Tea Towels", "Tupperware", "Cling Film", "Cutlery",
"Crockery" } };
public ExpListAdapter(Context context) {
this.context = context;
// initialised check
checkState = new HashMap<Integer, boolean[]>();
}
public Object getChild(int groupPosition, int childPosition) {
return childPosition;
}
//
public long getChildId(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return 0;
}
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final int mGroupPosition = groupPosition;
final int mChildPosition = childPosition;
CheckBox checkbox = new CheckBox(context);
checkbox.setOnCheckedChangeListener(null);
if (checkState.containsKey(mGroupPosition)) {
boolean getChecked[] = checkState.get(mGroupPosition);
checkbox.setChecked(getChecked[mChildPosition]);
} else {
boolean getChecked[] = new boolean[getChildrenCount(mGroupPosition)];
checkState.put(mGroupPosition, getChecked);
checkbox.setChecked(false);
}
checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
boolean getChecked[] = checkState.get(mGroupPosition);
getChecked[mChildPosition] = isChecked;
checkState.put(mGroupPosition, getChecked);
} else {
boolean getChecked[] = checkState.get(mGroupPosition);
getChecked[mChildPosition] = isChecked;
checkState.put(mGroupPosition, getChecked);
}
}
});
checkbox.setText(childList[groupPosition][childPosition]);
checkbox.setPadding(40, 0, 0, 0);
//SharedPreferences.Editor editor = inventorylistcheckStateData.edit();
//for (Entry<Integer, boolean[]> entry: checkState.entrySet()) editor.putBoolean(entry.getKey().toString(), entry.getValue());
return checkbox;
}
// returns the number of children you are having.
public int getChildrenCount(int groupPosition) {
// TODO Auto-generated method stub
return childList[groupPosition].length;
}
// returns the number of parents you have.
public Object getGroup(int groupPosition) {
return groupPosition;
}
public int getGroupCount() {
// TODO Auto-generated method stub
return parentList.length;
}
public long getGroupId(int groupPosition) {
// TODO Auto-generated method stub
return groupPosition;
}
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
TextView text = new TextView(context);
text.setText(parentList[groupPosition]);
text.setPadding(40, 0, 0, 0);
return text;
}
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return true;
}
}
Is there anyway i can save the checklists , or do I have to change everything?
SharedPreferences keyValues = getContext().getSharedPreferences("Your_Shared_Prefs"), Context.MODE_PRIVATE);
SharedPreferences.Editor keyValuesEditor = keyValues.edit();
for (String s : checklist.keySet()) {
keyValuesEditor.putString(s, checklist.get(s));
}
keyValuesEditor.commit();
Related
I am developer a Apps which contain Various Name & Country List. I want to pass Employee Name & Country name to another activity on click on Child Item of Expandable ListView.
How to set On Click Listener Method on my Activity?
package nasir.main.activity;
import java.util.ArrayList;
import nasir.adapter.EntryItem;
import nasir.adapter.MyListAdapter;
import nasir.adapter.SectionItem;
import nasir.bd.poem.R;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.SearchView;
public class Employee_List extends Activity implements SearchView.OnQueryTextListener, SearchView.OnCloseListener {
Button Collapse;
Button Expand;
private SearchView search;
private MyListAdapter listAdapter;
private ExpandableListView myList;
private ArrayList<SectionItem> section = new ArrayList<SectionItem>();
ArrayList<EntryItem> items = new ArrayList<EntryItem>();
ExpandableListView expandableList = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.poem_list);
expandableList = (ExpandableListView) findViewById(R.id.expandableList);
Expand = (Button) findViewById(R.id.Expand);
Collapse = (Button) findViewById(R.id.Collapse);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
search = (SearchView) findViewById(R.id.search);
search.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
search.setIconifiedByDefault(false);
search.setOnQueryTextListener(this);
search.setOnCloseListener(this);
Collapse.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int count = listAdapter.getGroupCount();
for (int i = 0; i < count; i++){
myList.collapseGroup(i);
}
Collapse.setVisibility(View.GONE);
Expand.setVisibility(View.VISIBLE);
}
});
Expand.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int count = listAdapter.getGroupCount();
for (int i = 0; i < count; i++){
myList.expandGroup(i);
}
Expand.setVisibility(View.GONE);
Collapse.setVisibility(View.VISIBLE);
}
});
// display the list
displayList();
// expand all Groups
// expandAll();
collapseAll();
}
// method to expand all groups
private void expandAll() {
int count = listAdapter.getGroupCount();
for (int i = 0; i < count; i++) {
myList.expandGroup(i);
}
}
//method to Collapse all groups
private void collapseAll() {
int count = listAdapter.getGroupCount();
for (int i = 0; i < count; i++){
myList.collapseGroup(i);
}
}
// method to expand all groups
private void displayList() {
// display the list
load_Part_1_Data();
// get reference to the ExpandableListView
myList = (ExpandableListView) findViewById(R.id.expandableList);
// create the adapter by passing your ArrayList data
listAdapter = new MyListAdapter(Poem_List.this, section);
// attach the adapter to the list
myList.setAdapter(listAdapter);
myList.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView arg0, View arg1, int arg2,
int arg3, long arg4) {
// TODO Auto-generated method stub
Intent intent = new Intent(Poem_List.this, Details_Information.class);
startActivity(intent);
return false;
}
});
}
private void load_Part_1_Data() {
items = new ArrayList<EntryItem>();
section.add(new SectionItem(R.drawable.ic_launcher, "", items));
items.add(new EntryItem(R.drawable.ic_launcher, "Margerate Milan", "Computer Operator", getString(R.string.app_name)));
items.add(new EntryItem(R.drawable.ic_launcher, "Abraham Jhon", "Salse Man", getString(R.string.app_name)));
items = new ArrayList<EntryItem>();
section.add(new SectionItem(R.drawable.blank_image, "", items));
items.add(new EntryItem(R.drawable.ic_launcher, "England", "Europe", getString(R.string.app_name)));
items.add(new EntryItem(R.drawable.ic_launcher, "Japan", "Asia", getString(R.string.app_name)));
}
#Override
public boolean onClose() {
listAdapter.filterData("");
expandAll();
return true;
}
#Override
public boolean onQueryTextChange(String query) {
listAdapter.filterData(query);
expandAll();
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
listAdapter.filterData(query);
expandAll();
return false;
}
}
MyListAdapter.Class
package nasir.adapter;
import java.util.ArrayList;
import nasir.bd.poem.R;
import nasir.main.activity.Details_Information;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MyListAdapter extends BaseExpandableListAdapter {
private Context context;
private ArrayList<SectionItem> continentList;
private ArrayList<SectionItem> originalList;
public MyListAdapter(Context context, ArrayList<SectionItem> continentList) {
this.context = context;
this.continentList = new ArrayList<SectionItem>();
this.continentList.addAll(continentList);
this.originalList = new ArrayList<SectionItem>();
this.originalList.addAll(continentList);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
ArrayList<EntryItem> countryList = continentList.get(groupPosition).getSectionList();
return countryList.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) {
final EntryItem country = (EntryItem) getChild(groupPosition, childPosition);
if (view == null) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.child_row, null);
}
ImageView Rank = (ImageView) view.findViewById(R.id.Rank);
TextView Poem = (TextView) view.findViewById(R.id.Poem);
TextView Poetry = (TextView) view.findViewById(R.id.Poetry);
Rank.setImageResource(country.getRank());
Poem.setText(country.getPoem().trim());
Poetry.setText(country.getPoetry().trim());
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, Details_Information.class);
Bundle bundle=new Bundle();
intent.putExtras(bundle);
intent.putExtra("header", country.getDetails_Doc());
context.startActivity(intent);
}
});
return view;
}
#Override
public int getChildrenCount(int groupPosition) {
ArrayList<EntryItem> countryList = continentList.get(groupPosition).getSectionList();
return countryList.size();
}
#Override
public Object getGroup(int groupPosition) {
return continentList.get(groupPosition);
}
#Override
public int getGroupCount() {
return continentList.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isLastChild, View view, ViewGroup parent) {
SectionItem continent = (SectionItem) getGroup(groupPosition);
if (view == null) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.group_row, null);
}
TextView heading = (TextView) view.findViewById(R.id.heading);
heading.setText(continent.getName().trim());
ImageView Group_icon = (ImageView) view.findViewById(R.id.Group_Icon);
Group_icon.setImageResource(continent.getIcon());
return view;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public void filterData(String query) {
query = query.toLowerCase();
Log.v("MyListAdapter", String.valueOf(continentList.size()));
continentList.clear();
if (query.isEmpty()) {
continentList.addAll(originalList);
} else {
for (SectionItem continent : originalList) {
ArrayList<EntryItem> countryList = continent.getSectionList();
ArrayList<EntryItem> newList = new ArrayList<EntryItem>();
for (EntryItem country : countryList) {
if (country.getPoem().toLowerCase().contains(query) || country.getPoetry().toLowerCase().contains(query) ) {
newList.add(country);
}
}
if (newList.size() > 0) {
SectionItem nContinent = new SectionItem(continent.getIcon(), continent.getName(), newList);
continentList.add(nContinent);
}
}
}
Log.v("MyListAdapter", String.valueOf(continentList.size()));
notifyDataSetChanged();
}
}
In the Employee_List activity , you can access the data through index of child and group obtaining from ChildClickListener
myList.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView arg0, View arg1, int arg2,
int arg3, long arg4) {
// TODO Auto-generated method stub
//Here You can access the child data by
final EntryItem country = (EntryItem) listAdapter .getChild(arg2, arg3);
//From here you can pass the data through Intent
...
return false;
}
});
I'm working on my project where I created Expandable List View with Men's and Women's sports. Each of them expands the list with sports like soccer, baseball, basketball, volleyball, golf. Now I'm at the point where I have to click on the one of the sports what gonna open new page, on that page will be presented previous games with results and upcoming events for each sport. All information's will be fetched from data base form athletic website. I do not how to make new page for individual sports with all information's what should be presented. Here is my code. Thanks in advance! Here is my code:
1)**MainActivity.java**
package com.example.athletic_project.java;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.Toast;
public class MainActivity<View> extends ActionBarActivity {
ExpandableListView exv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
exv=(ExpandableListView)findViewById(R.id.expandableListView1);
exv.setAdapter(new MyAdapter(this));
exv.setOnChildClickListener(new OnChildClickListener(){
#Override
public boolean onChildClick(ExpandableListView parent,
android.view.View v, int groupPosition, int childPosition,
long id) {
// TODO Auto-generated method stub
String itemclicked=MyAdapter.childList[groupPosition][childPosition];
Toast.makeText(MainActivity.this, itemclicked + " is clicked.", Toast.LENGTH_SHORT).show();
return false;
}
});
}
}
2)**MyAdapter.java**
package com.example.athletic_project.java;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
public class MyAdapter extends BaseExpandableListAdapter {
private Context context;
Typeface typeface;
static String []parentList = {"Men's Sports","Women's Sports"};
static String [][]childList = {
{
"Baseball","Basketball","Bowling","Cross Country","Golf","Soccer","Track & Field"
},
{
"Baseball","Basketball","Bowling","Cross Country","Golf","Soccer","Track & Field","Volleyball"
}
};
public MyAdapter(Context context) {
// TODO Auto-generated constructor stub
this.context=context;
}
#Override
public int getGroupCount() {
// TODO Auto-generated method stub
return parentList.length;
}
#Override
public int getChildrenCount(int groupPosition) {
// TODO Auto-generated method stub
return childList[groupPosition].length;
}
#Override
public Object getGroup(int groupPosition) {
// TODO Auto-generated method stub
return groupPosition;
}
#Override
public Object getChild(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getGroupId(int groupPosition) {
// TODO Auto-generated method stub
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return 0;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
typeface=Typeface.createFromAsset(context.getAssets(),"fonts/KGTribecaStamp.ttf");
TextView tv = new TextView(context);
tv.setText(parentList[groupPosition]);
tv.setPadding(45, 10, 10, 10);
tv.setTextSize(18);
tv.setTextColor(Color.BLUE);
tv.setTypeface(typeface);
return tv;
}
#Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
typeface=Typeface.createFromAsset(context.getAssets(),"fonts/KGTribecaStamp.ttf");
TextView tv = new TextView(context);
tv.setText(childList[groupPosition][childPosition]);
tv.setPadding(45, 10, 10, 10);
tv.setTextSize(15);
tv.setTextColor(Color.WHITE);
tv.setTypeface(typeface);
return tv;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return true;
}
}
3)**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"
android:background="#drawable/mtfinal"
>
<ExpandableListView
android:id="#+id/expandableListView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:dividerHeight="1.5dp"
>
</ExpandableListView>
</LinearLayout>
In addChildView add onClickListener like
tv.setOnClickListener(itemClick)
itemClick field of adapter. Initilize it from constructor (may be null of no clicks expected)
Also set to view tag
tv.setTag
Later in click listener get tag as key of pressed item and start your activity with this extra in intent to fetch appropriate data from DB to show
Like this
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
exv=(ExpandableListView)findViewById(R.id.expandableListView1);
exv.setAdapter(new MyAdapter(this, new OnClickListener() {
#Override
public void onClick(android.view.View v) {
// or any other key Object
if( v.getTag() instanceof String ) {
startPageActivity( (String)v.getTag());
}
}
}));
}
private void startPageActivity(String key) {
Intent intent=new Intent(MainActivity.this, SomeActivity.class);
intent.putExtra(KEY_NAME, key);
startActivity(intent);
}
public MyAdapter(Context context, OnClickListener listener) {
this.listener=listener;
this.context=context;
}
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
TextView tv = new TextView(context);
tv.setText(childList[groupPosition][childPosition]);
tv.setPadding(45, 10, 10, 10);
tv.setTextSize(15);
tv.setTextColor(Color.BLACK);
// setup listener
tv.setOnClickListener(listener);
// u may set any Object
tv.setTag(childList[groupPosition][childPosition]);
return tv;
}
public class SomeActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final String stringKey = getIntent().getExtras().getString(MainActivity.KEY_NAME);
//do something with passed key - fro example get data from DB to show
Toast.makeText(this, stringKey + " in new activity", Toast.LENGTH_SHORT).show();
}
}
I've read about 30 pages from SO as well as tutorials about tracking check states in lists but info (especially working info) is scarce on doing so in an Expandable ListView.
I've got the children populating with checkboxes but when I check a box on a child from 1 group, random children in other groups also check. I need to stop this. The best info I think I read was to set the checkbox as a separate tag but I don't know how to set multiple tags, when I tried, I got a class mismatch error comparing the checkbox to the convertview.
Has anybody come across a good way to keep track of checkbox states in an expandablelistview's children?
I've made multiple changes so I'm putting in the entire adapter code. Please check first few lines of getGroupView and entire getChildView and help me see what I'm doing wrong.
EDIT:
What's happening now is that when I check a box and then expand another group, all checked boxes uncheck:
public class MyExpandableListAdapter extends BaseExpandableListAdapter
implements OnCheckedChangeListener {
private Context mContext;
private ArrayList<ContactNameItems> mListDataHeader;
private HashMap<String, List<ContactPhoneItems>> mListDataChild;
private boolean[] mGetChecked;
private HashMap<String, boolean[]> mChildCheckStates;
private ArrayList<String> selectedNumbers;
private ChildViewHolder childViewHolder;
private GroupViewHolder groupViewHolder;
private String numberText;
public MyExpandableListAdapter(Context context,
ArrayList<ContactNameItems> listDataHeader,
HashMap<String, List<ContactPhoneItems>> listDataChild,
ArrayList<String> listOfNumbers) {
mContext = context;
mListDataHeader = listDataHeader;
mListDataChild = listDataChild;
selectedNumbers = listOfNumbers;
mChildCheckStates = new HashMap<String, boolean[]>();
}
#Override
public int getGroupCount() {
return mListDataHeader.size();
}
#Override
public ContactNameItems getGroup(int groupPosition) {
return mListDataHeader.get(groupPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String contactName = getGroup(groupPosition).getName();
Bitmap contactImage = getGroup(groupPosition).getImage();
mGetChecked = new boolean[getChildrenCount(groupPosition)];
mChildCheckStates.put(contactName, mGetChecked);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.contact_name_item, null);
groupViewHolder = new GroupViewHolder();
groupViewHolder.mContactName = (TextView) convertView
.findViewById(R.id.lblListHeader);
groupViewHolder.mContactImage = (ImageView) convertView
.findViewById(R.id.ivContactPhoto);
convertView.setTag(groupViewHolder);
} else {
groupViewHolder = (GroupViewHolder) convertView.getTag();
}
if (contactImage != null) {
groupViewHolder.mContactImage.setImageBitmap(contactImage);
} else {
groupViewHolder.mContactImage
.setImageResource(R.drawable.default_contact);
}
groupViewHolder.mContactName.setText(contactName);
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return mListDataChild.get(mListDataHeader.get(groupPosition).getName())
.size();
}
#Override
public ContactPhoneItems getChild(int groupPosition, int childPosition) {
return mListDataChild.get(mListDataHeader.get(groupPosition).getName())
.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 contactName = getGroup(groupPosition).getName();
final int mChildPosition = childPosition;
numberText = getChild(groupPosition, childPosition).getNumber();
String typeText = getChild(groupPosition, childPosition).getPhoneType();
mGetChecked = mChildCheckStates.get(contactName);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) this.mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.contact_detail_item, null);
childViewHolder = new ChildViewHolder();
childViewHolder.mPhoneNumber = (TextView) convertView
.findViewById(R.id.tv_phone_number);
childViewHolder.mPhoneType = (TextView) convertView
.findViewById(R.id.tv_phone_type);
childViewHolder.mCheckBox = (CheckBox) convertView
.findViewById(R.id.checkBox);
convertView.setTag(R.layout.contact_detail_item, childViewHolder);
} else {
childViewHolder = (ChildViewHolder) convertView
.getTag(R.layout.contact_detail_item);
}
childViewHolder.mPhoneNumber.setText(numberText);
childViewHolder.mPhoneType.setText(typeText);
childViewHolder.mCheckBox.setChecked(mGetChecked[mChildPosition]);
childViewHolder.mCheckBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
boolean isChecked = childViewHolder.mCheckBox.isChecked();
Log.d("Debug", "isChecked = " + String.valueOf(isChecked));
if (isChecked) {
selectedNumbers.add(numberText);
} else {
selectedNumbers.remove(numberText);
}
childViewHolder.mCheckBox.setChecked(isChecked);
mGetChecked[mChildPosition] = isChecked;
mChildCheckStates.put(contactName, mGetChecked);
}
});
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return false;
}
#Override
public boolean hasStableIds() {
return false;
}
public ArrayList<String> getSelectedNumbers() {
return selectedNumbers;
}
public final class GroupViewHolder {
TextView mContactName;
ImageView mContactImage;
}
public final class ChildViewHolder {
TextView mPhoneNumber;
TextView mPhoneType;
CheckBox mCheckBox;
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
Log.d("Debug", "onCheckChangedListener : " + String.valueOf(isChecked));
}
}
HERE IS THE WORKING SOLUTION
OK, although there seems to be a lot of suggestions on the internet about checkboxes in expandable listviews, none had worked for me. I was able to get it working with the help of a bunch of people, especially anddev84. Now I'm not going to claim that this is perfect or foolproof. I'm just claiming that it works for me. I've tested on 2 devices and I'm very pleased with it.
So I've taken my working code, dwindled it down to its essential parts and added a bunch of helpful comments so anybody who needs it can you it. Hopefully it works as well for you as it does for me. Enjoy
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
// Eclipse wanted me to use a sparse array instead of my hashmaps, I just suppressed that suggestion
#SuppressLint("UseSparseArrays")
public class MyExpandableListAdapter extends BaseExpandableListAdapter {
// Define activity context
private Context mContext;
/*
* Here we have a Hashmap containing a String key
* (can be Integer or other type but I was testing
* with contacts so I used contact name as the key)
*/
private HashMap<String, List<ExpListChildItems>> mListDataChild;
// ArrayList that is what each key in the above
// hashmap points to
private ArrayList<ExpListGroupItems> mListDataGroup;
// Hashmap for keeping track of our checkbox check states
private HashMap<Integer, boolean[]> mChildCheckStates;
// Our getChildView & getGroupView use the viewholder patter
// Here are the viewholders defined, the inner classes are
// at the bottom
private ChildViewHolder childViewHolder;
private GroupViewHolder groupViewHolder;
/*
* For the purpose of this document, I'm only using a single
* textview in the group (parent) and child, but you're limited only
* by your XML view for each group item :)
*/
private String groupText;
private String childText
/* Here's the constructor we'll use to pass in our calling
* activity's context, group items, and child items
*/
public MyExpandableListAdapter(Context context,
ArrayList<ExpListGroupItems> listDataGroup, HashMap<String, List<ExpListChildItems>> listDataChild) {
mContext = context;
mListDataGroup = listDataGroup;
mListDataChild = listDataChild;
// Initialize our hashmap containing our check states here
mChildCheckStates = new HashMap<Integer, boolean[]>();
}
#Override
public int getGroupCount() {
return mListDataGroup.size();
}
/*
* This defaults to "public object getGroup" if you auto import the methods
* I always make a point to change it from "object" to whatever item
* I passed through the constructor
*/
#Override
public ExpListGroupItems getGroup(int groupPosition) {
return mListDataGroup.get(groupPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
// I passed a text string into an activity holding a getter/setter
// which I passed in through "ExpListGroupItems".
// Here is where I call the getter to get that text
groupText = getGroup(groupPosition).getGroupText();
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.group_item, null);
// Initialize the GroupViewHolder defined at the bottom of this document
groupViewHolder = new GroupViewHolder();
groupViewHolder.mGroupText = (TextView) convertView.findViewById(R.id.groupTextView);
convertView.setTag(groupViewHolder);
} else {
groupViewHolder = (GroupViewHolder) convertView.getTag();
}
groupViewHolder.mGroupText.setText(groupText);
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return mListDataChild.get(mListDataGroup.get(groupPosition).getMyText()).size();
}
/*
* This defaults to "public object getChild" if you auto import the methods
* I always make a point to change it from "object" to whatever item
* I passed through the constructor
*/
#Override
public ExpListChildItems getChild(int groupPosition, int childPosition) {
return mListDataChild.get(mListDataGroup.get(groupPosition).getMyText()).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;
// I passed a text string into an activity holding a getter/setter
// which I passed in through "ExpListChildItems".
// Here is where I call the getter to get that text
childText = getChild(mGroupPosition, mChildPosition).getChildText();
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) this.mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.child_item, null);
childViewHolder = new ChildViewHolder();
childViewHolder.mChildText = (TextView) convertView
.findViewById(R.id.childTextView);
childViewHolder.mCheckBox = (CheckBox) convertView
.findViewById(R.id.checkBox);
convertView.setTag(R.layout.child_item, childViewHolder);
} else {
childViewHolder = (ChildViewHolder) convertView
.getTag(R.layout.child_item);
}
childViewHolder.mChildText.setText(childText);
/*
* You have to set the onCheckChangedListener to null
* before restoring check states because each call to
* "setChecked" is accompanied by a call to the
* onCheckChangedListener
*/
childViewHolder.mCheckBox.setOnCheckedChangeListener(null);
if (mChildCheckStates.containsKey(mGroupPosition)) {
/*
* if the hashmap mChildCheckStates<Integer, Boolean[]> contains
* the value of the parent view (group) of this child (aka, the key),
* then retrive the boolean array getChecked[]
*/
boolean getChecked[] = mChildCheckStates.get(mGroupPosition);
// set the check state of this position's checkbox based on the
// boolean value of getChecked[position]
childViewHolder.mCheckBox.setChecked(getChecked[mChildPosition]);
} else {
/*
* if the hashmap mChildCheckStates<Integer, Boolean[]> does not
* contain the value of the parent view (group) of this child (aka, the key),
* (aka, the key), then initialize getChecked[] as a new boolean array
* and set it's size to the total number of children associated with
* the parent group
*/
boolean getChecked[] = new boolean[getChildrenCount(mGroupPosition)];
// add getChecked[] to the mChildCheckStates hashmap using mGroupPosition as the key
mChildCheckStates.put(mGroupPosition, getChecked);
// set the check state of this position's checkbox based on the
// boolean value of getChecked[position]
childViewHolder.mCheckBox.setChecked(false);
}
childViewHolder.mCheckBox.setOnCheckedChangeListener(new 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);
}
}
});
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return false;
}
#Override
public boolean hasStableIds() {
return false;
}
public final class GroupViewHolder {
TextView mGroupText;
}
public final class ChildViewHolder {
TextView mChildText;
CheckBox mCheckBox;
}
}
I see you have a selectedNumbers object, what type of collection is that? It might make most sense to have a Map or List or some collection based on something more unique, like the group & child position. Then you can do this:
(EDIT: edited the code to make sure the checkedChangedListener doesn't trigger)
(EDIT 2 based on OP's update): You probably shouldn't use a map of Strings to boolean arrays. Instead try this. It's fairly similar but uses ints which will be more foolproof to compare than Strings
...
HashMap<Integer, Integer> mCheckedStates; // assume initialized as you did
...
childViewHolder.mPhoneNumber.setText(numberText);
childViewHolder.mPhoneType.setText(typeText);
childViewHolder.mCheckBox.setOnCheckedChangeListener(null);
if (mCheckedStates.contains(groupPosition)) {
int checkedChildren = mCheckedStates.get(groupPosition);
if ((checkedChildren & (1 << childPosition)) == 1) {
childViewHolder.mCheckBox.setChecked(true);
} else {
//Edit: Cannot rely on checkbox being false on Recycle,
childViewHolder.mCheckBox.setChecked(false);
}
}
childViewHolder.mCheckBox.setOnCheckedChangeListener(this);
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// get group and child positions
if (isChecked) {
if (mCheckedStates.contains(groupPosition)) {
// I'm using a bitmap to keep resources low, but it's not necessary to do it this way
int childmap = mCheckedStates.get(groupPosition);
childmap += (1 << childPosition);
mCheckedStates.put(groupPosition, childmap);
} else {
mCheckedStates.put(groupPosition, (1 << childPosition));
}
} else {
if (mCheckedStates.contains(groupPosition)) {
int childmap = mCheckedStates.get(groupPosition);
if (childmap == (1 << childPosition)) {
mCheckedStates.remove(groupPosition);
} else {
childmap &= ~(1 << childPosition);
mCheckedStates.put(groupPosition, childmap);
}
}
}
}
}
I was also the victim of the same problem and tried your solution and now its working like a charm. Thanks buddy. :)
I just modified the code with String instead of custom domain model for the ease of other people.
MainActivity.java
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.Toast;
public class MainActivity extends Activity {
List<String> groupList;
List<String> childList;
Map<String, List<String>> laptopCollection;
ExpandableListView expListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("-Test Exapansion-", "Nai Yara");
createGroupList();
createCollection();
expListView = (ExpandableListView) findViewById(R.id.laptop_list);
final MyExpandableListAdapter expListAdapter = new MyExpandableListAdapter
(getApplicationContext() ,
groupList, laptopCollection);
expListView.setAdapter(expListAdapter);
expListView.getHeaderViewsCount();
//expListView.expandGroup(1);
//expListView.expandGroup(2);
int numberOfHeaders = expListView.getExpandableListAdapter().getGroupCount();
Log.d("-Test Exapansion-", "Number of Groups are:"+numberOfHeaders);
for(int i = 0; i<numberOfHeaders; i++){
expListView.expandGroup(i);
}
setGroupIndicatorToRight();
expListView.setOnChildClickListener(new OnChildClickListener() {
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
final String selected = (String) expListAdapter.getChild(
groupPosition, childPosition);
Toast.makeText(getBaseContext(), selected, Toast.LENGTH_LONG)
.show();
return true;
}
});
}
private void createGroupList() {
groupList = new ArrayList<String>();
groupList.add("HP");
groupList.add("Dell");
groupList.add("Lenovo");
groupList.add("Sony");
groupList.add("HCL");
groupList.add("Samsung");
groupList.add("HTC");
}
private void createCollection() {
// preparing laptops collection(child)
String[] hpModels = { "HP Pavilion G6-2014TX", "ProBook HP 4540",
"HP Envy 4-1025TX" };
String[] hclModels = { "HCL S2101", "HCL L2102", "HCL V2002" };
String[] lenovoModels = { "IdeaPad Z Series", "Essential G Series",
"ThinkPad X Series", "Ideapad Z Series" };
String[] sonyModels = { "VAIO E Series", "VAIO Z Series",
"VAIO S Series", "VAIO YB Series" };
String[] dellModels = { "Inspiron", "Vostro", "XPS" };
String[] samsungModels = { "NP Series", "Series 5", "SF Series" };
String[] hTcModels = { "One", "One X", "Desire Series" };
laptopCollection = new LinkedHashMap<String, List<String>>();
for (String laptop : groupList) {
if (laptop.equals("HP")) {
loadChild(hpModels);
} else if (laptop.equals("Dell"))
loadChild(dellModels);
else if (laptop.equals("Sony"))
loadChild(sonyModels);
else if (laptop.equals("HCL"))
loadChild(hclModels);
else if (laptop.equals("Samsung"))
loadChild(samsungModels);
else if (laptop.equals("HTC"))
loadChild(hTcModels);
else
loadChild(lenovoModels);
laptopCollection.put(laptop, childList);
}
}
private void loadChild(String[] laptopModels) {
childList = new ArrayList<String>();
for (String model : laptopModels)
childList.add(model);
}
private void setGroupIndicatorToRight() {
/* Get the screen width */
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
expListView.setIndicatorBounds(width - getDipsFromPixel(35), width
- getDipsFromPixel(5));
}
// Convert pixel to dip
public int getDipsFromPixel(float pixels) {
// Get the screen's density scale
final float scale = getResources().getDisplayMetrics().density;
// Convert the dps to pixels, based on density scale
return (int) (pixels * scale + 0.5f);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
MyExpandableListAdapter.java
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.Toast;
public class MainActivity extends Activity {
List<String> groupList;
List<String> childList;
Map<String, List<String>> laptopCollection;
ExpandableListView expListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("-Test Exapansion-", "Nai Yara");
createGroupList();
createCollection();
expListView = (ExpandableListView) findViewById(R.id.laptop_list);
final MyExpandableListAdapter
expListAdapter =
new MyExpandableListAdapter(getApplicationContext()
, groupList, laptopCollection);
expListView.setAdapter(expListAdapter);
expListView.getHeaderViewsCount();
int numberOfHeaders = expListView.getExpandableListAdapter().getGroupCount();
Log.d("-Test Exapansion-", "Number of Groups are:"+numberOfHeaders);
for(int i = 0; i<numberOfHeaders; i++){
expListView.expandGroup(i);
}
setGroupIndicatorToRight();
expListView.setOnChildClickListener(new OnChildClickListener() {
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
final String selected = (String) expListAdapter.getChild(
groupPosition, childPosition);
Toast.makeText(getBaseContext(), selected, Toast.LENGTH_LONG)
.show();
return true;
}
});
}
private void createGroupList() {
groupList = new ArrayList<String>();
groupList.add("HP");
groupList.add("Dell");
groupList.add("Lenovo");
groupList.add("Sony");
groupList.add("HCL");
groupList.add("Samsung");
groupList.add("HTC");
}
private void createCollection() {
// preparing laptops collection(child)
String[] hpModels = { "HP Pavilion G6-2014TX", "ProBook HP 4540",
"HP Envy 4-1025TX" };
String[] hclModels = { "HCL S2101", "HCL L2102", "HCL V2002" };
String[] lenovoModels = { "IdeaPad Z Series", "Essential G Series",
"ThinkPad X Series", "Ideapad Z Series" };
String[] sonyModels = { "VAIO E Series", "VAIO Z Series",
"VAIO S Series", "VAIO YB Series" };
String[] dellModels = { "Inspiron", "Vostro", "XPS" };
String[] samsungModels = { "NP Series", "Series 5", "SF Series" };
String[] hTcModels = { "One", "One X", "Desire Series" };
laptopCollection = new LinkedHashMap<String, List<String>>();
for (String laptop : groupList) {
if (laptop.equals("HP")) {
loadChild(hpModels);
} else if (laptop.equals("Dell"))
loadChild(dellModels);
else if (laptop.equals("Sony"))
loadChild(sonyModels);
else if (laptop.equals("HCL"))
loadChild(hclModels);
else if (laptop.equals("Samsung"))
loadChild(samsungModels);
else if (laptop.equals("HTC"))
loadChild(hTcModels);
else
loadChild(lenovoModels);
laptopCollection.put(laptop, childList);
}
}
private void loadChild(String[] laptopModels) {
childList = new ArrayList<String>();
for (String model : laptopModels)
childList.add(model);
}
private void setGroupIndicatorToRight() {
/* Get the screen width */
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
expListView.setIndicatorBounds(width - getDipsFromPixel(35), width
- getDipsFromPixel(5));
}
// Convert pixel to dip
public int getDipsFromPixel(float pixels) {
// Get the screen's density scale
final float scale = getResources().getDisplayMetrics().density;
// Convert the dps to pixels, based on density scale
return (int) (pixels * scale + 0.5f);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
The problem is you use positions as ids. Position is not a id. Position may change and position of a child without group position is not unique identifier.
First You Have To Create New HashMap To Maintain The Child CheckBoxState in ExpandablelistView
Declare HashMap In Adapter As Like-
private HashMap mChildCheckStates;// New HashMap Created
Following Code Past In Your Adapter
cb.setOnCheckedChangeListener(null);
if (mChildCheckStates.containsKey(mGroupPosition)) {
boolean getChecked[] = mChildCheckStates.get(mGroupPosition);
cb.setChecked(getChecked[mChildPosition]);
}else {
boolean getChecked[] = new boolean[getChildrenCount(mGroupPosition)];
mChildCheckStates.put(mGroupPosition, getChecked);
cb.setChecked(false);
}
cb.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);
//Toast.makeText(mContext,"group-"+mGroupPosition+"child-"+mChildPosition,Toast.LENGTH_SHORT).show();
// String value=mListDataChild[0];
Toast.makeText(mContext,"-"+mListDataChild,Toast.LENGTH_SHORT).show();
} else {
boolean getChecked[] = mChildCheckStates.get(mGroupPosition);
getChecked[mChildPosition] = isChecked;
mChildCheckStates.put(mGroupPosition, getChecked);
Toast.makeText(mContext,"group-"+mGroupPosition+"child-"+mChildPosition,Toast.LENGTH_SHORT).show();
}
}
});
cb is checkbox.
I Hope This Logic I Help To AnyOne
Thanks
The problem I am having is the text that I type in the expanded view, is not being saved. The moment I close one group to open another, all the values saved in the first disappear. Can anyone advise me what to do so it can be saved not just for when I open the expandedView but also for when I restart it or resume it. I'm not sure how to use the onResume and onRestart functions. Thanks
I am attaching the code as well:
import android.content.Context;
import android.content.SharedPreferences;
import android.database.DataSetObserver;
import android.graphics.Color;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.TextView;
public class MyAdapter extends BaseExpandableListAdapter
{
private int counter;
SharedPreferences getPrefs;
private Context context;
String[] parent= new String [4];
String[][] child= new String [4][4];
String [][] weights= new String [4][4];
boolean KU=false;
boolean MC=false;
boolean TI=false;
boolean C=false;
boolean allEdited=false;
EditText et1;
EditText et2;
EditText et3;
EditText et4;
public MyAdapter(Context context)
{
this.context=context;
}
#Override
public Object getChild(int arg0, int arg1) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView,
ViewGroup parent)
{
counter++;
if (!allEdited)
{
et1= new EditText (context);
et2= new EditText (context);
et3= new EditText (context);
et4= new EditText (context);
child[groupPosition][0]=et1.getText().toString();
child[groupPosition][1]=et2.getText().toString();
child[groupPosition][2]=et3.getText().toString();
child[groupPosition][3]=et4.getText().toString();
}
if(!KU)
{
et1.setText(child[groupPosition][childPosition]);
et1.setPadding(50, 10, 10, 10);
et1.setTextSize(15);
et1.setTextColor(Color.WHITE);
et1.setFocusable(true);
et1.setInputType(0x00000002);
weights[groupPosition][0]=(et1.getText().toString());
}
if (!et1.getText().toString().equals(""))
{
KU=true;
}
if(KU)
{
et1.setText(weights[groupPosition][0]);
et1.setFreezesText(true);
}
if (!MC)
{
et2.setText(child[groupPosition][childPosition]);
et2.setPadding(50, 10, 10, 10);
et2.setTextSize(15);
et2.setTextColor(Color.WHITE);
et2.setFocusable(true);
et2.setInputType(0x00000002);
weights[groupPosition][1]=(et2.getText().toString());
}
else if (!et2.getText().toString().equals(""))
{
MC=true;
}
weights[groupPosition][1]=(et2.getText().toString());
if(MC)
{
et1.setText(weights[groupPosition][1]);
}
if (!TI)
{
et3.setText(child[groupPosition][childPosition]);
et3.setPadding(50, 10, 10, 10);
et3.setTextSize(15);
et3.setTextColor(Color.WHITE);
et3.setFocusable(true);
et3.setInputType(0x00000002);
weights[groupPosition][2]=(et3.getText().toString());
}
else if (!et3.getText().toString().equals(""))
{
TI=true;
}
weights[groupPosition][2]=(et3.getText().toString());
if(TI)
{
et3.setText(weights[groupPosition][2]);
}
if (!C)
{
et4.setText(child[groupPosition][childPosition]);
et4.setPadding(50, 10, 10, 10);
et4.setTextSize(15);
et4.setTextColor(Color.WHITE);
et4.setFocusable(true);
et4.setInputType(0x00000002);
weights[groupPosition][3]=(et4.getText().toString());
}
else if (!et4.getText().toString().equals(""))
{
C=true;
}
weights[groupPosition][3]=(et1.getText().toString());
if(C)
{
et4.setText(weights[groupPosition][3]);
}
if (KU && MC && TI && C)
{
allEdited=true;
}
if (counter==1)
return et1;
else if (counter==2)
return et2;
else if (counter==3)
return et3;
else if (counter==4)
return et4;
else
counter=0; return et1;
}
#Override
public int getChildrenCount(int groupPosition) {
// TODO Auto-generated method stub
return child[groupPosition].length;
}
#Override
public Object getGroup(int groupPosition) {
// TODO Auto-generated method stub
return groupPosition;
}
#Override
public int getGroupCount()
{
return parent.length;
}
#Override
public long getGroupId(int groupPosition)
{
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
{
TextView tv= new TextView (context);
this.parent[groupPosition]=tv.getText().toString();
getPrefs = PreferenceManager.getDefaultSharedPreferences(context);
String allCourses= getPrefs.getString("allClasses", "Please enter your course code");
String[] courses= allCourses.split(",");
for (int i=0;i<courses.length;i++)
{
this.parent[i]=courses[i];
}
tv.setText(this.parent[groupPosition]);
tv.setPadding(50, 10, 10, 10);
tv.setTextSize(20);
tv.setTextColor(Color.GREEN);
return tv;
}
you should use a Custom List Adapter, and whenever you type something in textview, have a list and assign it to the list for particular index(position)
As #Kapil said you can use list to store the values but those values will be destroyed once the activity is destroyed. If you want a permanent storage i.e. the values should remain even if you restart the app the should use Shared Preferences or SQLite Database.
i try to build a ExpandableListView with a own ExpandableListAdapter but the ExpandableListView is not visible in my activity :-(
Below you find my Source-Code.
Thanks for your help :-)
Greetings,
Kangee
Here the Code from the activity:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.group_main);
onCreateDBAndDBTabled();
mAddGroupButton = (Button) findViewById(R.id.Button_Add_Group);
mAddGroupButton.setOnClickListener(this);
mExpandableList = (ExpandableListView) findViewById(R.id.ExpandableListView01);
ArrayList<ExpandableListItem> valueTree = new ArrayList<ExpandableListItem>();
ExpandableListItem gp1 = new ExpandableListItem();
gp1.putProperty("name", "e");
ExpandableListItem gp11 = new ExpandableListItem();
gp11.putProperty("name", "l");
gp1.addChild(gp11);
ExpandableListItem gp2 = new ExpandableListItem();
gp2.putProperty("name", "A");
ExpandableListItem gp22 = new ExpandableListItem();
gp22.putProperty("name", "B");
ExpandableListItem gp23 = new ExpandableListItem();
gp23.putProperty("name", "A1");
ExpandableListItem gp24 = new ExpandableListItem();
gp24.putProperty("name", "A3");
ExpandableListItem gp25 = new ExpandableListItem();
gp25.putProperty("name", "A4");
gp2.addChild(gp22);
gp2.addChild(gp23);
gp2.addChild(gp24);
gp2.addChild(gp25);
valueTree.add(gp1);
valueTree.add(gp2);
Log.d("onCreate", "hasChild " + gp1.hasChilds());
Log.d("onCreate", "hasChild " + gp2.hasChilds());
MyColoredExpandableListAdapter adapter = new MyColoredExpandableListAdapter(this, valueTree);
mExpandableList.setAdapter(adapter);
}
Code MyColoredExpandableListAdapter:
private class MyColoredExpandableListAdapter extends MyExpandableListAdapter{
public MyColoredExpandableListAdapter(Context context,
ArrayList<ExpandableListItem> valueTree) {
super(context, valueTree);
Log.d("MyColoredExpandableListAdapter", "Group Count" + this.getGroupCount());
for(int i = 0; i < this.getGroupCount(); i++)
Log.d("MyColoredExpandableListAdapter", "Child Count" + this.getChildrenCount(i));
// TODO Auto-generated constructor stub
}
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Log.d("getChildView", "GO INTO");
if(convertView == null){
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(R.layout.group_exp_childs, null);
}
TextView text = (TextView) convertView.findViewById(R.id.TextView_Group_EXP_Childs);
text.setText(">>" + this.mValueTree.get(groupPosition).getChild(childPosition).getProperty("name"));
return convertView;
}
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Log.d("getGroupView", "GO INTO");
if(convertView == null){
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(R.layout.group_exp_childs, null);
}
TextView text = (TextView) convertView.findViewById(R.id.TextView_Group_EXP_Childs);
text.setText(">" + this.mValueTree.get(groupPosition).getProperty("name"));
return convertView;
}
}
Code MyExpandableListAdapter:
public abstract class MyExpandableListAdapter extends BaseExpandableListAdapter {
protected Context mContext;
protected ArrayList<ExpandableListItem> mValueTree;
public MyExpandableListAdapter(Context context,
ArrayList<ExpandableListItem> valueTree)
{
mContext = context;
mValueTree = valueTree;
}
public Object getChild(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
if(mValueTree.get(groupPosition).hasChilds())
return mValueTree.get(groupPosition).getChild(childPosition);
return null;
}
public long getChildId(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return childPosition; // WE NEED NO SPECIAL ID
}
public int getChildrenCount(int groupPosition) {
// TODO Auto-generated method stub
if(mValueTree.get(groupPosition).hasChilds())
return mValueTree.get(groupPosition).sizeOfChilds();
return 0;
}
public Object getGroup(int groupPosition) {
// TODO Auto-generated method stub
return mValueTree.get(groupPosition);
}
public int getGroupCount() {
// TODO Auto-generated method stub
return mValueTree.size();
}
public long getGroupId(int groupPosition) {
// TODO Auto-generated method stub
return groupPosition; // WE NEED NO SPECIAL ID
}
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return true;
}
}
Code ExpandableListItem:
public class ExpandableListItem {
private HashMap<String,String> properties = new HashMap<String,String>();
public void clearProperties() {
properties.clear();
}
public boolean containsPropertyKey(String key) {
return properties.containsKey(key);
}
public boolean containsPropertyValue(String value) {
return properties.containsValue(value);
}
public String getProperty(String key) {
return properties.get(key);
}
public boolean hasProperties() {
return !properties.isEmpty();
}
public String putProperty(String key, String value) {
return properties.put(key, value);
}
public String removeProperty(String key) {
return properties.remove(key);
}
public int sizeOfProperties() {
return properties.size();
}
public String[] propertiesKeys()
{
int count = 0;
String[] result = new String[sizeOfProperties()];
for(String key : this.properties.keySet())
result[count++] = key;
return result;
}
private ArrayList<ExpandableListItem> childs = new ArrayList<ExpandableListItem>();
public boolean addChild(ExpandableListItem object) {
return childs.add(object);
}
public void clearChilds() {
childs.clear();
}
public ExpandableListItem getChild(int index) {
return childs.get(index);
}
public boolean hasChilds() {
return !childs.isEmpty();
}
public ExpandableListItem removeChild(int index) {
return childs.remove(index);
}
public int sizeOfChilds() {
return childs.size();
}
}
The Code of the Layouts (Without Tag):
R.id.TextView_Group_EXP_Childs :
?xml version="1.0" encoding="utf-8"?
LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingLeft="20dp" android:id="#+id/TextView_Group_EXP_Childs" android:text=">>"/TextView
/LinearLayout