I have followed this example tutorial and developed a sample application http://www.androidhive.info/2013/07/android-expandable-list-view-tutorial/
If i click on Core i want to load one more list in the same Screen under Core,How Could i do this?using my below code i am able to load the child list in another Screen,help?
My Code for ChildClickListener goes here:
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// TODO Auto-generated method stub
Log.d("onChildClick", "onChildClick");
String position = (String) parentItems.get(groupPosition);
Log.d("position", position);
String child = listDataChild.get(position).get(childPosition);
Log.d("child", child);
if (child.equalsIgnoreCase("Core")) {
ArrayList<String> parentItems = new ArrayList<String>();
HashMap<String, List<String>> listDataChild = new HashMap<String, List<String>>();
ArrayList<String> childItems = new ArrayList<String>();
childItems.add("corejava");
childItems.add("corejava");
childItems.add("corejava");
childItems.add("corejava");
parentItems.add(position);
listDataChild.put(parentItems.get(0), childItems);
expandableList = (ExpandableListView) findViewById(R.id.lvExp);
CoreAdapter adapter = new CoreAdapter(parentItems,
listDataChild);
CustExpListview SecondLevelexplv = new CustExpListview(
MainActivity.this);
adapter.setInflater(
(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE),
MainActivity.this);
SecondLevelexplv.setAdapter(adapter);
SecondLevelexplv.setGroupIndicator(null);
expandableList.setAdapter(adapter);
}
i write one treeView adapter for you, you can use this and put many level as you want, for that you need just copy following code:
MainActivity:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// add data for test on one list<AccountHierarchical>
AccountHierarchical obj = new AccountHierarchical();
obj.setLevelId(1);
obj.setTitle("level 1");
AccountHierarchical obj2 = new AccountHierarchical();
obj2.setLevelId(1);
obj2.setTitle("level 2");
AccountHierarchical obj3 = new AccountHierarchical();
obj3.setLevelId(1);
obj3.setTitle("level 3");
List<AccountHierarchical> emptyList = new ArrayList<AccountHierarchical>();
obj3.setList(emptyList);
List<AccountHierarchical> list2 = new ArrayList<AccountHierarchical>();
list2.add(obj3);list2.add(obj3);list2.add(obj3);list2.add(obj3);list2.add(obj3);
obj2.setList(list2);
List<AccountHierarchical> list = new ArrayList<AccountHierarchical>();
list.add(obj2);list.add(obj2);list.add(obj2);list.add(obj2);list.add(obj2);
obj.setList(list);
List<AccountHierarchical> result = new ArrayList<AccountHierarchical>();
result.add(obj);result.add(obj);result.add(obj);result.add(obj);
// create Adapter
TreeView adapter = new TreeView(result, this,
getLayoutInflater() , false, 0);
ExpandableListView expandList = (ExpandableListView)findViewById(R.id.expandableList_tree);
expandList.setGroupIndicator(null);
expandList.setAdapter(adapter);
}
CustExpListview:
public class CustExpListview extends ExpandableListView {
int intGroupPosition, intChildPosition, intGroupid;
public CustExpListview(Context context) {
super(context);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// widthMeasureSpec = MeasureSpec.makeMeasureSpec(400,
// MeasureSpec.AT_MOST);
heightMeasureSpec = MeasureSpec.makeMeasureSpec(600,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
AccountHierarchical:
public class AccountHierarchical {
List<AccountHierarchical> list;
private String Title;
private int Id;
public int getId() {
return Id;
}
public void setLevelId(int Id) {
this.Id = Id;
}
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public List<AccountHierarchical> getList() {
return list;
}
public void setList(List<AccountHierarchical> list) {
this.list = list;
}
}
TreeView:
public class TreeView extends BaseExpandableListAdapter implements
OnClickListener {
List<AccountHierarchical> list;
LayoutInflater inflatter;
static Context context;
boolean checkGroup;
int position;
static ProgressDialog ProgressDialog;
public TreeView( List<AccountHierarchical> list, Context context,
LayoutInflater inflatter, boolean checkGroup, int position
) {
this.list = list;
TreeView.context = context;
this.inflatter = inflatter;
this.checkGroup = checkGroup; // this is true when you call from inner.
this.position = position;
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return list.get(groupPosition).getList().get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return list.get(groupPosition).getList().get(childPosition).getId();
}
#Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
if (checkGroup)
groupPosition = position;
List<AccountHierarchical> childtemp = list.get(groupPosition)
.getList();
// call this adapter again for creating another level
if (childtemp.get(childPosition).getList().size() > 0) {
CustExpListview SecondLevelexplv = new CustExpListview(context);
TreeView adapter = null;
adapter = new TreeView(childtemp, context,
inflatter, true, childPosition);
SecondLevelexplv.setGroupIndicator(null);
SecondLevelexplv.setAdapter(adapter);
return SecondLevelexplv;
}
// call one layout, this is last child
else {
convertView = inflatter.inflate(R.layout.grouprow, null);
TextView tv = (TextView) convertView.findViewById(R.id.grouprow);
tv.setText(list.get(groupPosition).getList().get(childPosition)
.getTitle());
tv.setPadding(0, 0, 20, 0);
convertView.setTag(list.get(groupPosition).getList()
.get(childPosition) );
convertView.setId(position);
convertView.setOnClickListener(this);
return convertView;
}
}
#Override
public int getChildrenCount(int groupPosition) {
return list.get(groupPosition).getList().size();
}
#Override
public Object getGroup(int groupPosition) {
return list.get(groupPosition);
}
#Override
public int getGroupCount() {
if (checkGroup)
return 1;
return list.size();
}
#Override
public long getGroupId(int groupPosition) {
return list.get(groupPosition).getId();
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
if (convertView == null)
convertView = inflatter.inflate(R.layout.grouprow, null);
TextView tv = (TextView) convertView.findViewById(R.id.grouprow);
if (checkGroup)
tv.setText(list.get(position).getTitle());
else
tv.setText(list.get(groupPosition).getTitle());
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return false;
}
#Override
public void onClick(View v) {
// your onClick method
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<ExpandableListView
android:id="#+id/expandableList_tree"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ExpandableListView>
</RelativeLayout>
grouprow.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/grouprow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginBottom="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:text=""/>
</RelativeLayout>
snap:
You have to create a layout in the xml file (from where your core textview comes from) and display an image view below
onClick of that imageView you will just have to make your layout Gone and Visible
I have just given you direction rest relies on your skill :)
<RelativeLayout
android:id="#+id/option"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:gravity="center"
android:orientation="horizontal" >
</RelativeLayout>
<RelativeLayout
android:id="#+id/linear"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:orientation="horizontal" >
<ImageView
android:id="#+id/navigationIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:src="#drawable/nn" />
<ImageView
android:id="#+id/callOption"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/phonee" />
<ImageView
android:id="#+id/imageViewfeedback"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:src="#drawable/editer" />
</RelativeLayout>
In Jave File
linear.setVisibility(View.GONE);
option.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
if(count==0)
{
linear.setVisibility(View.VISIBLE);
count=1;
}
else
{
linear.setVisibility(View.GONE);
count=0;
}
}
});
You need to switch to Three-Level of Expandable ListView which contains the subchild inside child.
Also check out ExpandableListView with 3 Childs
Related
My code java. I'm getting data from the intent as an array. I am using arraylist,listview and custom adapter. I can show the incoming data using listview. I want the item I clicked to be deleted. The name of my delete button "deleteshop" in customadapter. How can I do that ?
My code;
final ListView list = findViewById(R.id.list);
final ArrayList<SubjectData> arrayList = new ArrayList<SubjectData>();
final String[] cartList = getIntent().getStringArrayExtra("saleData");
arrayList.add(new SubjectData("", ""));
final int cartListLength = cartList.length;
int counter = 0;
String lastItem = "";
for (String e : cartList) {
counter += 1;
if (e == "" || e == null) {
lastItem = cartList[counter-3];
break;
}
String productPhoto = "";
switch (e) {
case "1 PC GREEN COLA x 10.00 TL":
productPhoto = "cc";
break;
default:
productPhoto = "";
break; }
arrayList.add(new SubjectData(e, productPhoto));;
}
arrayList.remove(arrayList.size()-1);
arrayList.remove(arrayList.size()-1);
arrayList.add(new SubjectData("*** GRAND TOTAL TL:" + lastItem + " ***", "arrowgreen"));
arrayList.add(new SubjectData("", ""));
arrayList.add(new SubjectData("", ""));
final CustomAdapter customAdapter = new CustomAdapter(this, arrayList);
list.setAdapter(customAdapter);
SubjectData model class:
String SubjectName;
String Image;
public SubjectData(String subjectName, String image) {
this.SubjectName = subjectName;
this.Image = image;
}
Customadapter;
class CustomAdapter implements ListAdapter {
ArrayList<SubjectData> arrayList;
Context context;
public CustomAdapter(Context context, ArrayList<SubjectData> arrayList) {
this.arrayList=arrayList;
this.context=context;
}
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEnabled(int position) {
return true;
}
#Override
public void registerDataSetObserver(DataSetObserver observer) {
}
#Override
public void unregisterDataSetObserver(DataSetObserver observer) {
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final SubjectData subjectData=arrayList.get(position);
if(convertView==null){
LayoutInflater layoutInflater = LayoutInflater.from(context);
convertView=layoutInflater.inflate(R.layout.list_row, null);
TextView tittle=convertView.findViewById(R.id.title);
ImageView imag=convertView.findViewById(R.id.list_image);
ImageView
deleteshop=convertView.findViewById(R.id.deleteshop);
deleteshop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "Deneme",
Toast.LENGTH_SHORT).show();
}
});
tittle.setText(subjectData.SubjectName);
Resources resources = context.getResources();
final int resourceId = resources.getIdentifier(subjectData.Image, "drawable",
context.getPackageName());
imag.setImageResource(resourceId);
}
return convertView;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return arrayList.size();
}
#Override
public boolean isEmpty() {
return false;
}
listview design;
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dip">
<LinearLayout
android:id="#+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginRight="5dip"
android:padding="3dip">
<ImageView
android:id="#+id/list_image"
android:layout_width="50dip"
android:layout_height="50dip" />
</LinearLayout>
<TextView
android:id="#+id/title"
android:layout_width="250dp"
android:layout_height="match_parent"
android:layout_alignTop="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:gravity="center"
android:textColor="#040404"
android:textSize="15dip"
android:textStyle="bold"
android:typeface="sans" />
<ImageView
android:layout_gravity="center"
android:id="#+id/deleteshop"
android:src="#drawable/negative"
android:layout_width="25dp"
android:layout_height="25dp" ></ImageView>
</LinearLayout>
If you want to delete clicked item from your list view then you can use this code .I tested and its deleting smoothly , after deleting its updating list also.
CustomAdapter customAdapter = new CustomAdapter(this,R.layout.list_row, arrayList);
list.setAdapter(customAdapter);
// after setting adapter put this code
// and update your ui again using set adapter
Log.e("Custom",""+arrayList.size());
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
arrayList.remove(i);
list.setAdapter(customAdapter);
}
});
This is not a best solution but ulternative , suppose if you want to update your adapter on click of deletebutton first create one interface , here is sample
public interface MyInterface{
public void deleteItem(int pos);
}
Now in your main activity use like this MainActivity extends AppCompatActivity implements MyInterface and place your interface method public void deleteItem(int pos){ arrayList.remove(pos); list.setAdapter(customAdapter); }
After that call this method from your adapter like below
deleteshop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "Delete",
Toast.LENGTH_SHORT).show();
//Actually change your list of items here
if (context instanceof SampleList) {
((MainActivity)context).deleteItem(position);
}
}
});
I have a problem statement in my booking app such that user can delete all the booking of the particular date or all the dates, see this image:
I have tried to add data to the grid view using multiple adapters for listview and the inner gridview, but it's taking data replication. How can I solve this problem?
Each date represents the listview with checkbox,and the UH,U1 etc represents the item of gridview. I want to pass the selected venue id ie. UH,U! etc in a listview and its corresponding dates
Try the sample below :)
MainActivity.java:
public class MainActivity extends Activity {
Button clearChecks;
ExpandableListView expandableListView;
ExpandableListGridAdapter 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);
List<String> listTitle = genGroupList();
expandableListAdapter = new ExpandableListGridAdapter(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();
}
});
}
private List<String> genGroupList(){
List<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));
testDataList.add(testItem);
}
listChild.put(header.get(i), testDataList);
}
return listChild;
}
}
ChildItemSample.java:
public class ChildItemSample {
private boolean checked;
private String name;
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ChildItemSample(){
checked = false;
name = "";
}
public ChildItemSample(String name){
checked = false;
this.name = name;
}
}
ExpandableListGridAdapter.java:
public class ExpandableListGridAdapter extends BaseExpandableListAdapter {
private Context context;
private List<String> listGroup;
private Map<String, List<ChildItemSample>> listChild;
private int checkedBoxesCount;
private boolean[] checkedGroup;
public ExpandableListGridAdapter(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 1;
}
#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, listChild.get(listGroup.get(groupPosition)).size()));
if(checkedGroup[groupPosition]) groupViewHolder.cbGroup.setChecked(true);
else groupViewHolder.cbGroup.setChecked(false);
groupViewHolder.cbGroup.setTag(groupPosition);
return view;
}
#Override
public View getChildView(final int groupPosition, int childPosition, boolean b, View view, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_grid_item, null);
GridLayout childLayout = view.findViewById(R.id.layout_child);
for(int i = 0; i < listChild.get(listGroup.get(groupPosition)).size(); i++){
ChildItemSample expandedListText = getChild(groupPosition, i);
CheckBox cbChild = new CheckBox(context);
GridLayout.LayoutParams params = new GridLayout.LayoutParams();
params.width = (int)(80 * context.getResources().getDisplayMetrics().density);
cbChild.setLayoutParams(params);
cbChild.setChecked(expandedListText.isChecked());
cbChild.setText(expandedListText.getName());
cbChild.setTag(i);
childLayout.addView(cbChild);
cbChild.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CheckBox cb = (CheckBox) view;
int pos = (int) view.getTag();;
ChildItemSample selectedItem = listChild.get(listGroup.get(groupPosition)).get(pos);
selectedItem.setChecked(cb.isChecked());
if(cb.isChecked()){
checkedBoxesCount++;
Toast.makeText(context,"Checked value is: " +
listChild.get(listGroup.get(groupPosition)).get(pos).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();
}
});
}
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;
}
}
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">
<Button
android:id="#+id/btnClearChecks"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Clear Checks" />
<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>
list_grid_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout_child"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="60dp"
android:columnCount="3"
android:orientation="horizontal">
</GridLayout>
Hope that helps!
I am searching for a way to load data into an Expandale List View, the output I want to resemble the one of the picture attached here
In order this to be done dynamically, is it better to be read from a csv? Or to create a DB? Furthermore, on a sub-item press, I want a ScrollView to appear.
Here is the code so far:
The layout of the activity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ExpandableListView
android:id= "#+id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<TextView
android:id="#+id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
The itemlayout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView android:id="#+id/grp_child"
android:paddingLeft="50dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
And the subitem:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView android:id="#+id/row_name"
android:paddingLeft="50dp"
android:focusable="false"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
In the activity, I have hardcoded some values so far, using some tutorials I came across:
public void onCreate(Bundle savedInstanceState) {
try{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photographers);
SimpleExpandableListAdapter expListAdapter =
new SimpleExpandableListAdapter(
this,
createGroupList(),
R.layout.group_row,
new String[] { "Group Item" },
new int[] { R.id.row_name },
createChildList(),
R.layout.child_row,
new String[] {"Sub Item"},
new int[] { R.id.grp_child}
);
setListAdapter( expListAdapter );
}catch(Exception e){
System.out.println("Errrr +++ " + e.getMessage());
}
}
/* Creating the Hashmap for the row */
#SuppressWarnings("unchecked")
private List createGroupList() {
ArrayList result = new ArrayList();
for( int i = 0 ; i < 15 ; ++i ) { // 15 groups........
HashMap m = new HashMap();
m.put( "Group Item","Group Item " + i ); // the key and it's value.
result.add( m );
}
return (List)result;
}
#SuppressWarnings("unchecked")
private List createChildList() {
ArrayList result = new ArrayList();
for( int i = 0 ; i < 15 ; ++i ) { // this -15 is the number of groups(Here it's fifteen)
/* each group need each HashMap-Here for each group we have 3 subgroups */
ArrayList secList = new ArrayList();
for( int n = 0 ; n < 3 ; n++ ) {
HashMap child = new HashMap();
child.put( "Sub Item", "Sub Item " + n );
secList.add( child );
}
result.add( secList );
}
return result;
}
public void onContentChanged () {
System.out.println("onContentChanged");
super.onContentChanged();
}
/* This function is called on each child click */
public boolean onChildClick( ExpandableListView parent, View v, int groupPosition,int childPosition,long id) {
System.out.println("Inside onChildClick at groupPosition = " + groupPosition +" Child clicked at position " + childPosition);
return true;
}
/* This function is called on expansion of the group */
public void onGroupExpand (int groupPosition) {
try{
System.out.println("Group expanding Listener => groupPosition = " + groupPosition);
}catch(Exception e){
System.out.println(" groupPosition Errrr +++ " + e.getMessage());
}
}
I am wondering if it is a good idea to store the data I want to show in separate csv files (one storing the data for the items, one for the subitems. one for the extra information in the ScrollView), to have id-s for identification and to directly read from the CSVs with the OpenCSVReader?
I would appreciate any pieces of advice,
Thanks
create adapter for your expandable listView. like that
public class ExpandableAdapter extends BaseExpandableListAdapter {
private final Context context;
private final List<Menu> parentObjects;
public ExpandableAdapter(Context context, ArrayList<Menu> parentObjects) {
this.context = context;
this.parentObjects = parentObjects;
}
#Override
public int getGroupCount() {
return parentObjects.size();
}
#Override
public int getChildrenCount(int i) {
return parentObjects.get(i).childMenu.size();
}
#Override
public Menu getGroup(int i) {
return parentObjects.get(i);
}
#Override
public Menu.ChildMenu getChild(int i, int i2) {
return parentObjects.get(i).childMenu.get(i2);
}
#Override
public long getGroupId(int i) {
return i;
}
#Override
public long getChildId(int i, int i2) {
return 0;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {
Menu currentParent = parentObjects.get(i);
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context
.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.navdrawer_parent_item, viewGroup,false);
}
ImageView imageViewIndicator = (ImageView) view.findViewById(R.id.imageViewNav);
if (getChildrenCount(i) == 0)
imageViewIndicator.setVisibility(View.GONE);
else
imageViewIndicator.setVisibility(View.VISIBLE);
TextView textViewNavMenuName = (TextView) view.findViewById(R.id.textViewNavParentMenuName);
ImageView imageViewIcon = (ImageView) view.findViewById(R.id.imageViewIcon);
String base64 = currentParent.getImage();
if (base64 != null && !base64.equals("")) {
byte[] imageAsBytes = Base64.decode(currentParent.getImage().getBytes(), Base64
.DEFAULT);
imageViewIcon.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0,
imageAsBytes.length));
} else
imageViewIcon.setImageResource(R.drawable.ic_action_android);
textViewNavMenuName.setText(currentParent.getMenuName());
return view;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean b, View view,
ViewGroup viewGroup) {
Menu currentChild = getGroup(groupPosition);
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context
.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.navdrawer_child_item, viewGroup,false);
}
View divider = view.findViewById(R.id.divider);
if (b)
divider.setVisibility(View.VISIBLE);
else
divider.setVisibility(View.GONE);
TextView textViewNavMenuName = (TextView) view.findViewById(R.id.textViewNavChildMenuName);
textViewNavMenuName.setText(currentChild.childMenu.get(childPosition).getMenuName());
return view;
}
#Override
public boolean isChildSelectable(int i, int i2) {
return true;
}
}
and the model for the expandable listView like
public class Menu {
private int AssociatedApp;
private String MenuName;
private String NavigateURL;
private String ActivityName;
private String Image;
private int MenuID;
public ArrayList<ChildMenu> childMenu;
public ArrayList<ChildMenu> getChildMenu() {
return childMenu;
}
public void setChildMenu(ArrayList<ChildMenu> childMenu) {
this.childMenu = childMenu;
}
public int getAssociatedApp() {
return AssociatedApp;
}
public void setAssociatedApp(int associatedApp) {
AssociatedApp = associatedApp;
}
public String getMenuName() {
return MenuName;
}
public void setMenuName(String menuName) {
MenuName = menuName;
}
public String getNavigateURL() {
return NavigateURL;
}
public void setNavigateURL(String navigateURL) {
NavigateURL = navigateURL;
}
public String getActivityName() {
return ActivityName;
}
public void setActivityName(String activityName) {
ActivityName = activityName;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
public Menu() {
}
public int getMenuID() {
return MenuID;
}
public class ChildMenu {
private int AssociatedApp;
private String MenuName;
private String NavigateURL;
private String ActivityName;
private String Image;
private int MenuID;
public ChildMenu(String menuName, String activityName) {
this.MenuName = menuName;
this.ActivityName=activityName;
}
public ChildMenu() {
}
public int getAssociatedApp() {
return AssociatedApp;
}
public void setAssociatedApp(int associatedApp) {
AssociatedApp = associatedApp;
}
public String getMenuName() {
return MenuName;
}
public void setMenuName(String menuName) {
MenuName = menuName;
}
public String getNavigateURL() {
return NavigateURL;
}
public void setNavigateURL(String navigateURL) {
NavigateURL = navigateURL;
}
public String getActivityName() {
return ActivityName;
}
public void setActivityName(String activityName) {
ActivityName = activityName;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
public int getMenuID() {
return MenuID;
}
}
}
ok now you can create your menu with data and bindwith expandable listview
elv = (ExpandableListView)findViewById(R.id.elv);
elv.setOnGroupExpandListener(onGroupExpandListenser);
MyExpandableAdapter adapter = new MyExpandableAdapter(this, getData());//where getData() will return list of data.
elv.setAdapter(adapter);
parent xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:paddingBottom="12dp"
android:paddingLeft="12dp"
android:paddingTop="12dp">
<ImageView
android:contentDescription="#string/app_name"
android:id="#+id/imageViewIcon"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_alignParentLeft="true"
android:layout_margin="4dp"
/>
<TextView
android:id="#+id/textViewNavParentMenuName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_centerVertical="true"
android:layout_toLeftOf="#+id/imageViewNav"
android:layout_toRightOf="#+id/imageViewIcon"
android:padding="10dp"
android:textSize="15sp"/>
<ImageView
android:contentDescription="#string/app_name"
android:id="#+id/imageViewNav"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_margin="4dp"
android:src="#drawable/ic_action_more_nav"
/>
</RelativeLayout>
<include
layout="#layout/divider"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
child 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="wrap_content"
android:gravity="center_vertical"
android:orientation="vertical">
<TextView
android:id="#+id/textViewNavChildMenuName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="45dp"
android:gravity="center_vertical"
android:text="TextView"
android:padding="16dp"/>
<include
layout="#layout/divider"
android:layout_width="match_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
adding listener for expandable listView like this. groupExpandlistener is used for collasping other groups while open one
private int lastExpandedPosition = -1;
for setting up listener
elv.setOnChildClickListener(new DrawerItemClickListener());
elv.setOnGroupClickListener(new DrawerItemClickListener());
elv.setOnGroupExpandListener(new DrawerItemClickListener());
private class DrawerItemClickListener implements ExpandableListView.OnChildClickListener,
ExpandableListView.OnGroupClickListener, ExpandableListView.OnGroupExpandListener {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int
childPosition, long id) {
selectItem(childPosition, navigationConfig.getBaseExpandableListAdapter
().getChild
(groupPosition, childPosition));
return true;
}
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
selectItem(groupPosition, navigationConfig.getBaseExpandableListAdapter
().getGroup
(groupPosition));
return false;
}
#Override
public void onGroupExpand(int groupPosition) {
if (lastExpandedPosition != -1
&& groupPosition != lastExpandedPosition) {
expandableListView.collapseGroup(lastExpandedPosition);
}
lastExpandedPosition = groupPosition;
}
}
for sample data use to bind with getData(). note create constructor in model class as given in getData()
//Sample data for expandable list view.
public List<Menu> getData()
{
List<Menu> parentObjects = new ArrayList<Menu>();
for (int i = 0; i<20; i++)
{
parentObjects.add(new Menu("Mother " +i, "Father " +i, "Header " + i, "Footer " +i, getChildren(i)));
}
return parentObjects;
}
private List<Menu.ChildMenu> getChildren(int childCount)
{
List<Menu.ChildMenu> childObjects = new ArrayList<Menu.ChildMenu>();
for (int i =0; i<childCount; i++)
{
childObjects.add(new Menu.ChildMenu("Child " + (i+1), 10 +i ));
}
return childObjects;
}
In the shopping cart activity I have a listview and I have placed a imagebutton on top of it as shown in the class_list_group.xml. When start of the activity I want to hide the imagebutton. But once press the edit button in the action bar (onOptionsItemSelected in the activity class) I want to display a relative layout which is carrying the imagebutton as shown in the xml file.
That is my question, my problem is how can I do it? any help will be appreciated. It crahses from what I have done saying null point exception.
Shoppingcartactivity.java class
public class ShoppingCartActivity extends Activity {
private TextView totalTV;
private TextView discountTV;
private TextView totalExclTV;
private TextView totalTaxTV;
private TextView netPriceTV;
private ProductAdapter mProductAdapter;
private ExpandableListView expListView;
private EditText couponET;
private ImageButton couponBTN;
private List<Product> mCartList;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
private String Strdiscount;
private double discount;
public JSONObject DiscountObj;
private double addSubTotal;
RelativeLayout hiddenEditDelete;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cart_activity);
ActionBar actionBar = getActionBar();
getActionBar().setIcon(
new ColorDrawable(getResources().getColor(
android.R.color.transparent)));
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
// Enabling Back navigation on Action Bar icon
actionBar.setDisplayHomeAsUpEnabled(true);
mCartList = ShoppingCartHelper.getCartList();
expListView = (ExpandableListView) findViewById(R.id.lvExp);
mProductAdapter = new ProductAdapter(this, mCartList,
getLayoutInflater(), true);
// setting list adapter
expListView.setAdapter(mProductAdapter);
totalTV = (TextView) findViewById(R.id.total_valueamount);
discountTV = (TextView) findViewById(R.id.discount_valueamount);
totalExclTV = (TextView) findViewById(R.id.exl_tax_valueamount);
totalTaxTV = (TextView) findViewById(R.id.ttl_tax_valueamount);
netPriceTV = (TextView) findViewById(R.id.net_price_valueamount);
couponBTN = (ImageButton) findViewById(R.id.btncoupon);
couponET = (EditText) findViewById(R.id.ET_coupon);
hiddenEditDelete = (RelativeLayout) findViewById(R.id.rl_cartedit);
hiddenEditDelete.setVisibility(View.GONE);
couponET.setEnabled(false);
couponBTN.setEnabled(false);
priceCalculation();
double taxamount = (addSubTotal * 5) / 100;
double netTotal = addSubTotal + taxamount;
DecimalFormat df = new DecimalFormat("#.##");
addSubTotal = Double.valueOf(df.format(addSubTotal));
taxamount = Double.valueOf(df.format(taxamount));
netTotal = Double.valueOf(df.format(netTotal));
totalTV.setText(Double.toString(addSubTotal));
discountTV.setText("0.0");
totalExclTV.setText(Double.toString(addSubTotal));
totalTaxTV.setText(Double.toString(taxamount));
netPriceTV.setText(Double.toString(netTotal));
// couponBTN.setOnClickListener(new View.OnClickListener() {
// public void onClick(View v) {
//
// try {
// String CouponCode = couponET.getText().toString();
//
// if (!Utility.isNotNull(CouponCode)) {
// Toast.makeText(getApplicationContext(),
// "Insert coupon code", Toast.LENGTH_LONG).show();
// } else {
// new CouponAsyncTask(ShoppingCartActivity.this)
// .execute(CouponCode);
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// });
}
public void loadCouponData() {
Strdiscount = DiscountObj.optString("Discount");
try {
Log.i("Discount", DiscountObj.getString("Discount"));
} catch (JSONException e) {
e.printStackTrace();
}
}
public void priceCalculation() {
for (int i = 0; i < mCartList.size(); i++) {
if (!mCartList.isEmpty()) {
couponET.setEnabled(true);
couponBTN.setEnabled(true);
}
Product cat = mCartList.get(i);
addSubTotal += cat.subTotal;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_cart, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
finish();
overridePendingTransition(R.anim.slide_in_left,
R.anim.slide_out_right);
return true;
case R.id.action_edit:
hiddenEditDelete.setVisibility(View.VISIBLE);
overridePendingTransition(R.anim.slide_in_right,
R.anim.slide_out_left);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
class_list_group.xml class
<?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"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/shareLILayout1"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:orientation="horizontal"
android:paddingTop="3dp"
android:weightSum="5" >
<TextView
android:id="#+id/lblListHeader"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_weight="3"
android:paddingBottom="4dp"
android:paddingLeft="28dp"
android:paddingTop="4dp"
android:singleLine="true"
android:textColor="#000000"
android:textSize="13sp"
android:textStyle="bold" />
</LinearLayout>
<RelativeLayout
android:id="#+id/rl_cartedit"
android:layout_width="60dp"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:gravity="center"
android:orientation="horizontal"
android:paddingBottom="4dp" >
<ImageButton
android:id="#+id/btneditcartitem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:background="#ffffff"
android:src="#drawable/edititem" />
</RelativeLayout>
</RelativeLayout>
ProductAdapter .java
public class ProductAdapter extends BaseExpandableListAdapter {
private List<Product> mCartList;
private Context _context;
private List<Product> _cartList;
private boolean mShowQuantity;
public ProductAdapter(Context context, List<Product> cartList,
LayoutInflater inflater, boolean showQuantity) {
this._context = context;
this._cartList = cartList;
mShowQuantity = showQuantity;
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return _cartList.get(groupPosition).getItems().get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return _cartList.get(groupPosition).getItems().get(childPosition)
.hashCode();
}
#Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) _context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.cart_list_item, parent, false);
}
TextView itemSize = (TextView) v.findViewById(R.id.lblListItemSize);
Item det = _cartList.get(groupPosition).getItems().get(childPosition);
itemSize.setText(det.itemName + " ( " + det.price + " ) ");
mCartList = ShoppingCartHelper.getCartList();
return v;
}
#Override
public int getChildrenCount(int groupPosition) {
int size = _cartList.get(groupPosition).getItems().size();
System.out.println("Child for group [" + groupPosition + "] is ["
+ size + "]");
return size;
}
#Override
public Object getGroup(int groupPosition) {
return this._cartList.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._cartList.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(final int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) _context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.cart_list_group, parent, false);
}
TextView groupName = (TextView) v.findViewById(R.id.lblListHeader);
TextView groupQty = (TextView) v.findViewById(R.id.lbl_qty);
TextView groupSubtotal = (TextView) v.findViewById(R.id.lblsubtotal);
final Product cat = _cartList.get(groupPosition);
// ShoppingCartEntry catalog = ShoppingCartHelper.getByProduct(cat);
// int productIndex = getIntent().getExtras().getInt(
// ShoppingCartHelper.PRODUCT_INDEX);
// final Product selectedProduct = catalog.get(productIndex);
groupName.setText(cat.description);
groupQty.setText(String.valueOf(cat.quantity));
groupSubtotal.setText(Double.toString(cat.subTotal));
ImageButton editIB = (ImageButton) v.findViewById(R.id.btneditcartitem);
if (cat.itemCategory != null && cat.itemCategory.equals("Pizza"))
editIB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent next = new Intent(_context, ActivityEdit.class);
Bundle b = new Bundle();
b.putDouble("subTotal", cat.subTotal);
next.putExtras(b);
next.putExtra("description", cat.description);
_context.startActivity(next);
((Activity) _context).overridePendingTransition(
R.anim.slide_in_right, R.anim.slide_out_left);
}
});
return v;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
cart_Activity
<ExpandableListView
android:id="#+id/lvExp"
android:layout_width="match_parent"
android:layout_height="162dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/grid_topics"
android:cacheColorHint="#00000000"
android:groupIndicator="#drawable/group_indicator" >
</ExpandableListView>
You haven't initialized hiddenEditDelete before using it in the onCreate method and that's why NPE is thrown. Also, I believe setContentView should be called last
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
expListView = (ExpandableListView) findViewById(R.id.lvExp);
mProductAdapter = new ProductAdapter(this, mCartList,
getLayoutInflater(), true);
expListView.setAdapter(mProductAdapter);
hiddenEditDelete = (RelativeLayout) findViewById(R.id.rl_cartedit);
hiddenEditDelete.setVisibility(View.GONE);
setContentView(R.layout.cart_activity);
}
The problem is you haven't took any reference for hiddenEditDelete (like expListView) before accessing it , You have to instantiate it with the proper layout id before using it. Then and then you can do whatever you want with the layout. Everything else is correct in onCreate()
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cart_activity);
expListView = (ExpandableListView) findViewById(R.id.lvExp);
mProductAdapter = new ProductAdapter(this, mCartList,
getLayoutInflater(), true);
expListView.setAdapter(mProductAdapter);
hiddenEditDelete.setVisibility(View.GONE);
}
Problem is with checkbox. When user click on child, app should show toast message on which child user clicked. It works fine if I click on textview of child, but when i click on checkbox, nothing heppend. Also when I click on child item, I want that my checkbox change state. Do you see something that I can't see. Here is my code for main activity
private ExpandableAdapter adapter;
private ExpandableListView expandableList;
private List<Pitanja> pitanjas = new ArrayList<Pitanja>();
private ArrayList<Pitanja> listaPitanja = new ArrayList<Pitanja>();
private List<Odgovor> odgovors = new ArrayList<Odgovor>();
public static HashMap<Integer, Integer> pitanjaa;
private Intent intent;
private ProgressDialog pDialog;
private TextView output;
private List<Ispit> ispitList;
private String pozicija;
private Button posalji;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ispit);
output = (TextView) findViewById(R.id.ispit_datum);
output.setMovementMethod(new ScrollingMovementMethod());
pitanjaa = new HashMap<Integer, Integer>();
posalji = (Button) findViewById(R.id.posaljiIspitButton);
posalji.setOnClickListener(this);
generateData();
initEx();
intent = getIntent();
RequestPackage p = new RequestPackage();
p.setUri("http://arka.foi.hr/WebDiP/2012_projekti/WebDiP2012_085/AIR/ispit.php");
p.setMethod("POST");
p.setParam("id_kolegij", intent.getStringExtra("id_predmeta"));
Log.i("Saljem podatke ", intent.getStringExtra("id_predmeta"));
MyTask task = new MyTask();
task.execute(p);
}
private void updateDisplay(){
Collections.shuffle(ispitList);
output.setText(String.valueOf(ispitList.get(0).getId()));
MyRequest task = new MyRequest();//this works fine
RequestPackage r = new RequestPackage();//works
r.setMethod("POST");//works
r.setUri("http://arka.foi.hr/WebDiP/2012_projekti/WebDiP2012_085/AIR/pitanja.php");//works
r.setParam("id_kolegij", output.getText().toString());//works
task.execute(r);
}
private void initEx(){
adapter = new ExpandableAdapter(IspitActivity.this, listaPitanja);
expandableList = (ExpandableListView) findViewById(R.id.expandableIspitListView);
expandableList.setAdapter(adapter);
for (int i=0;i<adapter.getGroupCount();i++){
expandableList.collapseGroup(i);
}
expandableList.setOnChildClickListener(new OnChildClickListener(){
#Override
public boolean onChildClick(ExpandableListView arg0, View arg1,
int arg2, int arg3, long arg4) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Klikno si na " + adapter.getChild(arg2, arg3).getText() + " " + adapter.getChild(arg2, arg3).getTocan_netocan(), Toast.LENGTH_SHORT).show();
if (Integer.parseInt(adapter.getChild(arg2, arg3).getTocan_netocan()) == 0)
pitanjaa.put(arg2, arg3);
Log.i("pitanja koja si odgovorio su", pitanjaa.toString());
adapter.getChild(arg2, arg3).setSelected(true);
return true;
}
});
}
private void generateData(){
Pitanja p;
for (int i=0;i<pitanjas.size();i++){
ArrayList<Odgovor> od = new ArrayList<Odgovor>();
for (int z=0;z<odgovors.size();z++){
if (odgovors.get(z).getId_pitanja().contains(String.valueOf(pitanjas.get(i).getId()))){
od.add(odgovors.get(z));
}
}
pozicija = pitanjas.get(i).getText();
p = new Pitanja(i, pozicija, od);
listaPitanja.add(p);
}
}
private class MyTask extends AsyncTask<RequestPackage, String, List<Ispit>>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(IspitActivity.this);
pDialog.setMessage("Dobavljam podatke...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected List<Ispit> doInBackground(RequestPackage... params) {
String content = HttpManager.getData(params[0]);
ispitList = JSONParser.parseIspit(content.substring(1, content.length()-1));
Log.i("Parsirano izgleda sljedeci", content.substring(1, content.length()-1));
return ispitList;
}
#Override
protected void onPostExecute(List<Ispit> result) {
super.onPostExecute(result);
pDialog.dismiss();
updateDisplay();
}
}
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), PregledActivity.class);
startActivity(intent);
}
}
Here is my expandablelistview adapter
public class ExpandableAdapter extends BaseExpandableListAdapter{
LayoutInflater inflater;
private List<Pitanja> groups;
public ExpandableAdapter(Context context,List<Pitanja> groups) {
super();
this.groups=groups;
inflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(Odgovor child,Pitanja group) {
if(!groups.contains(group)) {
groups.add(group);
}
int index=groups.indexOf(group);
ArrayList<Odgovor> ch=groups.get(index).getOdgovors();
ch.add(child);
groups.get(index).setOdgovors(ch);
}
public Odgovor getChild(int groupPosition, int childPosition) {
ArrayList<Odgovor> ch=groups.get(groupPosition).getOdgovors();
return ch.get(childPosition);
}
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public int getChildrenCount(int groupPosition) {
ArrayList<Odgovor> ch=groups.get(groupPosition).getOdgovors();
return ch.size();
}
public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
View convertView, ViewGroup parent) {
Odgovor child= (Odgovor) getChild(groupPosition,childPosition);
TextView childName=null;
CheckBox cb = null;
if(convertView==null) {
convertView=inflater.inflate(R.layout.child_item, null);
}
childName=(TextView) convertView.findViewById(R.id.textview_child_item);
childName.setText(child.getText());
cb = (CheckBox) convertView.findViewById(R.id.checkbox_child_item);
if (child.isSelected())
cb.setChecked(true);
return convertView;
}
public Pitanja getGroup(int groupPosition) {
return groups.get(groupPosition);
}
public int getGroupCount() {
return groups.size();
}
public long getGroupId(int groupPosition) {
return groupPosition;
}
public View getGroupView(final int groupPosition, boolean isExpanded, View convertView,
ViewGroup parent) {
TextView groupName = null;
Pitanja group=(Pitanja) getGroup(groupPosition);
if(convertView==null) {
convertView=inflater.inflate(R.layout.parent_item, null);
}
groupName=(TextView) convertView.findViewById(R.id.parent_item);
groupName.setText(group.getText());
return convertView;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public boolean hasStableIds() {
return true;
}
}
my child view
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<CheckBox
android:id="#+id/checkbox_child_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false" />
<TextView
android:id="#+id/textview_child_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
If I changle focusable of my checkbox, it doesn't work too. Someone have idea
The CheckBox will consume the click event before passing it on to the ExpandableListView click event. You'll need to manually attached a click listener to the CheckBox in the getChildView() method if you want to see those click events.