[Adapter class]
public class CustomExpandableListAdapter extends BaseExpandableListAdapter {
private Context context;
private List<String> expandableListTitle;
private HashMap<String, List<FilterList>> expandableListDetail;
private boolean checked;
private int lastClickedPosition;
private List<Boolean> setValueForSeletedFilter;
private String[] keysOfHashmap;
public CustomExpandableListAdapter(Context context, List<String> expandableListTitle,
HashMap<String, List<FilterList>> expandableListDetail, List<Boolean> setValueForSeletedFilter) {
this.context = context;
this.expandableListTitle = expandableListTitle;
this.expandableListDetail = expandableListDetail;
this.setValueForSeletedFilter = setValueForSeletedFilter;
}
#Override
public Object getChild(int listPosition, int expandedListPosition) {
return this.expandableListDetail.get(this.expandableListTitle.get(listPosition))
.get(expandedListPosition).getSearchFilterValue();
}
#Override
public long getChildId(int listPosition, int expandedListPosition) {
return expandedListPosition;
}
#Override
public View getChildView(final int listPosition, final int expandedListPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String expandedListText = (String) getChild(listPosition, expandedListPosition);
if (convertView == null) {
int i = listPosition;
int j = expandedListPosition;
LayoutInflater layoutInflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.list_item, null);
TextView expandedListTextView = (TextView) convertView
.findViewById(R.id.expandedListItem);
expandedListTextView.setText(expandedListText);
String s = expandableListTitle.get(listPosition);
final ImageView imageView = (ImageView) convertView.findViewById(R.id.iv_select);
if (setValueForSeletedFilter.get(expandedListPosition) == true) {
imageView.setVisibility(View.VISIBLE);
} else {
imageView.setVisibility(View.GONE);
}
}
return convertView;
}
private void toggleSelection(int i, View v) {
int j = i;
ImageView imageView = (ImageView) v.findViewById(R.id.iv_select);
imageView.setImageResource(R.drawable.ic_review);
}
#Override
public int getChildrenCount(int listPosition) {
return this.expandableListDetail.get(this.expandableListTitle.get(listPosition))
.size();
}
#Override
public Object getGroup(int listPosition) {
return this.expandableListTitle.get(listPosition);
}
#Override
public int getGroupCount() {
return this.expandableListTitle.size();
}
#Override
public long getGroupId(int listPosition) {
return listPosition;
}
#Override
public View getGroupView(int listPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String listTitle = (String) getGroup(listPosition);
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.list_group, null);
}
TextView listTitleTextView = (TextView) convertView
.findViewById(R.id.listTitle);
listTitleTextView.setTypeface(null, Typeface.BOLD);
listTitleTextView.setText(listTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return true;
}
public void setData(){
notifyDataSetChanged();
}
#Override
public boolean isChildSelectable(int listPosition, int expandedListPosition) {
return true;
}
}
[setting values for adapter class and notifying adapter on changing values]
final HashMap> setValueForSeletedFilter = new HashMap<>();
String header = null;
final List booleanList = new ArrayList<>();
final HashMap> stringListHashMap = new HashMap<>();
final List expandableListTitle;
for (int i = 0; i < filtersInfos.size(); i++) {
stringListHashMap.put(filtersInfos.get(i).getFilterHeaderName(), filtersInfos.get(i).getFilterLists());
if (filtersInfos.get(i).getFilterHeaderName().equalsIgnoreCase("Distance")) {
header = filtersInfos.get(i).getFilterHeaderName();
for (int j = 0; j < filtersInfos.get(i).getFilterLists().size(); j++)
booleanList.add(false);
}
}
setValueForSeletedFilter.put(header, booleanList);
expandableListTitle = new ArrayList<String>(stringListHashMap.keySet());
final CustomExpandableListAdapter adapter = new CustomExpandableListAdapter(this, expandableListTitle, stringListHashMap, booleanList);
expandableListView.setAdapter(adapter);
filterDialog.show();
expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
Toast.makeText(getApplicationContext(),
expandableListTitle.get(groupPosition) + " List Expanded.",
Toast.LENGTH_SHORT).show();
}
});
expandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
Toast.makeText(getApplicationContext(),
expandableListTitle.get(groupPosition) + " List Collapsed.",
Toast.LENGTH_SHORT).show();
}
});
final boolean[] checked = {false};
final int[] lastClickedPosition = {0};
expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
if (expandableListTitle.get(groupPosition).equalsIgnoreCase("Distance")) {
booleanList.add(childPosition, true);
setValueForSeletedFilter.put(expandableListTitle.get(groupPosition), booleanList);
expandableListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
return false;
}
});
close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
filterDialog.dismiss();
}
});
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
on the basis of header make list single or multi selection android.
getChildView() example for my case "Single selection"
#Override
public View getChildView(final int i, final int i1, boolean b, View view, ViewGroup viewGroup) {
View v = LayoutInflater.from(context).inflate(R.layout.expandablelv_child, null);
final CheckBox checkBox = v.findViewById(R.id.expandable_lv_child_cb);
RelativeLayout quantityContainer = v.findViewById(R.id.expandable_lv_child_quantity_cont);
final TextView textView = v.findViewById(R.id.expandable_lv_child_quantity_tv);
checkBox.setText(children.get(i).get(i1).getItemName());
double d=Double.parseDouble(children.get(i).get(i1).getMinQty());
int k=(int)d;
textView.setText(String.valueOf(k));
quantityContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
QuantityDialog dialog = new QuantityDialog(context, children.get(i).get(i1).getMinQty(),
children.get(i).get(i1).getMaxQty(), new DialogSelectable() {
#Override
public void onQuantitySelected(String quantity) {
if (group[i].parent == 1 && group[i].child == i1)
textView.setText(quantity);
ExpandableLvAdapter.quantity[i] = quantity;
}
});
dialog.show();
}
});
try {
// if (model.children.get(i).size() < children.get(i).size()) {
try {
model.children.get(i).add(checkBox);
} catch (Exception e) {
ArrayList<CheckBox> temp = new ArrayList<>();
temp.add(checkBox);
model.children.add(temp);
}
//}
} catch (Exception e) {
try {
model.children.get(i).add(checkBox);
} catch (Exception ex) {
ArrayList<CheckBox> temp = new ArrayList<>();
temp.add(checkBox);
model.children.add(temp);
}
}
if (group[i].parent == 1) {
model.children.get(i).get(group[i].child).setEnabled(true);
model.children.get(i).get(group[i].child).setChecked(true);
model.disable(i, children.get(i).get(group[i].child).getItemName());
} else {
model.enable(i);
}
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
group[i].parent = 1;
group[i].child = i1;
model.disable(i, children.get(i).get(i1).getItemName());
selected.add(children.get(i).get(i1));
quantity[i] = children.get(i).get(i1).getMaxQty();
} else {
group[i].parent = 0;
model.enable(i);
}
}
});
return v;
}
Related
Hi I followed this Example and implemented expandablelist that keeps track of its childitems(check boxes). I just wanted to extend this feature. I want to keep track of checkbox ,spinner and edittext. I did the following changes but got array index error. Someone please help me to do the same.
Update: I made some progress. I preserved checkbox state. Still edittext and spinner pending.
public class ServiceListAdapter extends BaseExpandableListAdapter {
private Context mContext;
private HashMap<ServiceListModel, List<ServiceListModel>> mListDataChild;
private ArrayList<ServiceListModel> mListDataGroup;
// Hashmap for keeping track of our checkbox check states
private HashMap<Integer, List<ServiceListModel>> mChildCheckStates;
private ChildViewHolder childViewHolder;
private GroupViewHolder groupViewHolder;
private ServiceListModel groupService, childService;
#SuppressLint("UseSparseArrays")
public ServiceListAdapter(Context context, ArrayList<ServiceListModel> listDataGroup, HashMap<ServiceListModel, List<ServiceListModel>> listDataChild) {
mContext = context;
mListDataGroup = listDataGroup;
mListDataChild = listDataChild;
// Initialize our hashmap containing our check states here
mChildCheckStates = new HashMap<>();
}
public int getNumberOfCheckedItemsInGroup(int mGroupPosition) {
List<ServiceListModel> services= mChildCheckStates.get(mGroupPosition);
int count = 0;
if (services != null) {
for (int j = 0; j < services.size(); ++j) {
if (services.get(j).isSelected()) count++;
}
}
return count;
}
#Override
public int getGroupCount() {
return mListDataGroup.size();
}
#Override
public ServiceListModel 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) {
groupService = getGroup(groupPosition);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.nav_list_group_header, null);
groupViewHolder = new GroupViewHolder();
groupViewHolder.mGroupText = convertView.findViewById(R.id.lblListHeader);
convertView.setTag(groupViewHolder);
} else {
groupViewHolder = (GroupViewHolder) convertView.getTag();
}
groupViewHolder.mGroupText.setText(groupService.getMenuName());
final ImageView arrow = convertView.findViewById(R.id.arrow);
if (getGroup(groupPosition).isHasChildren()) {
arrow.setVisibility(View.VISIBLE);
} else arrow.setVisibility(View.GONE);
if (isExpanded) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
arrow.setImageDrawable(mContext.getDrawable(R.drawable.ic_arrow_up));
} else
arrow.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ic_arrow_up));
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
arrow.setImageDrawable(mContext.getDrawable(R.drawable.ic_arrow_down));
} else
arrow.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ic_arrow_down));
}
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return mListDataChild.get(mListDataGroup.get(groupPosition)).size();
}
#Override
public ServiceListModel getChild(int groupPosition, int childPosition) {
return mListDataChild.get(mListDataGroup.get(groupPosition)).get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
ServiceListModel serviceListModel= getChild(groupPosition, childPosition);
final int mGroupPosition = groupPosition;
final int mChildPosition = childPosition;
childService = getChild(mGroupPosition, mChildPosition);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) this.mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.services_child_item, null);
childViewHolder = new ChildViewHolder();
childViewHolder.mCheckBox = convertView.findViewById(R.id.serviceCheckBox);
childViewHolder.feeET = convertView.findViewById(R.id.feeET);
childViewHolder.daysSpinner = convertView.findViewById(R.id.daysSpinner);
convertView.setTag(R.layout.services_child_item, childViewHolder);
} else {
childViewHolder = (ChildViewHolder) convertView.getTag(R.layout.services_child_item);
}
childViewHolder.mCheckBox.setText(childService.getMenuName());
childViewHolder.mCheckBox.setOnCheckedChangeListener(null);
if (mChildCheckStates.containsKey(mGroupPosition)) {
List<ServiceListModel> services = mChildCheckStates.get(mGroupPosition);
childViewHolder.mCheckBox.setChecked(services.get(mChildPosition).isSelected());
childViewHolder.feeET.setText(services.get(mChildPosition).getFees());
} else {
List<ServiceListModel> serModel=mListDataChild.get(mListDataGroup.get(groupPosition));
mChildCheckStates.put(mGroupPosition, serModel);
childViewHolder.mCheckBox.setChecked(false);
childViewHolder.feeET.setText("");
}
final List<KeyPairBoolData> days = new ArrayList<>();
KeyPairBoolData h = new KeyPairBoolData();
h.setId(1);
h.setName("1-3 Days");
h.setSelected(false);
days.add(h);
h = new KeyPairBoolData();
h.setId(2);
h.setName("3-7 Days");
h.setSelected(false);
days.add(h);
h = new KeyPairBoolData();
h.setId(3);
h.setName("7-15 Days");
h.setSelected(false);
days.add(h);
h = new KeyPairBoolData();
h.setId(3);
h.setName("Above 15 Days");
h.setSelected(false);
days.add(h);
childViewHolder.daysSpinner.setItems(days, -1, new SpinnerListener() {
#Override
public void onItemsSelected(List<KeyPairBoolData> items) {
for (int i = 0; i < items.size(); i++) {
if (items.get(i).isSelected()) {
Log.i("blb07", i + " : " + items.get(i).getName() + " : " + items.get(i).isSelected());
}
}
}
});
childViewHolder.mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
List<ServiceListModel> serv= mChildCheckStates.get(mGroupPosition);
serv.get(mChildPosition).setSelected(isChecked);
mChildCheckStates.put(mGroupPosition, serv);
}
});
childViewHolder.feeET.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
Log.i("blb07","before "+s);
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.i("blb07","On "+s);
}
#Override
public void afterTextChanged(Editable s) {
Log.i("blb07","after "+s);
List<ServiceListModel> serv= mChildCheckStates.get(mGroupPosition);
serv.get(mChildPosition).setFees(s.toString());
mChildCheckStates.put(mGroupPosition, serv);
}
});
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 {
SingleSpinner daysSpinner;
CheckBox mCheckBox;
EditText feeET;
}
}
The model class
public class ServiceListModel {
public boolean hasChildren, isGroup;
private String menuName, fees, days;
private int id;
private boolean selected;
public ServiceListModel(int id, String menuName, boolean isGroup, boolean hasChildren) {
this.menuName = menuName;
this.isGroup = isGroup;
this.hasChildren = hasChildren;
this.id = id;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMenuName() {
return menuName;
}
public void setMenuName(String menuName) {
this.menuName = menuName;
}
public String getFees() {
return fees;
}
public void setFees(String fees) {
this.fees = fees;
}
public String getDays() {
return days;
}
public void setDays(String days) {
this.days = days;
}
}
I have not tested it but the problem could be in your loop using preincrement instead of postincrement:
public int getNumberOfCheckedItemsInGroup(int mGroupPosition) {
List<ServiceListModel> services= mChildCheckStates.get(mGroupPosition);
int count = 0;
if (services != null) {
for (int j = 0; j < services.size(); ++j) {
if (services.get(j).isSelected()) count++;
}
}
return count;
}
I guess for should be for (int j = 0; j < services.size(); j++)
I have a check list (Customized expandable list view) that I am populating through adapter. I want to retrieve an array from adapter to Activity on click of a text view in activity.
Activity is as follows, I want to retrieve data in onOptionsItemSelected function:
public class MyPreferencesActivity extends BaseActivity implements PreferencesContract.View, AdapterView.OnItemClickListener, ExpandableListView.OnGroupClickListener {
private PreferencesContract.Presenter mPresenterPreferences;
private Context context;
private ExpandableListView elvListView;
private ArrayList<CategoryModel> categories;
private ExpandableListAdapter ela;
private List<CategoryModel> mCategories;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_preferences);
this.context = this;
Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
setupActionbar(toolbar, getString(R.string.preferneces), true, R.drawable.ab_home);
new PreferencesPresenter(this,
Injection.provideUseCaseHandler(),
Injection.provideGetCategories(getApplicationContext())
);
mPresenterPreferences.getCategories();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_save_my_preferences, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
//listener for home
switch (menuItem.getItemId()) {
case R.id.menu_create_event:
break;
}
return super.onOptionsItemSelected(menuItem);
}
private void populateList() {
categories = new ArrayList<>();
for (int i = 0; i < mCategories.size(); i ++){
categories.add(new CategoryModel(mCategories.get(i).getCategoryName(), mCategories.get(i).getCategoryId(), mCategories.get(i).getSubCategories()));
}
}
#Override
public void onItemClick(AdapterView<?> adapterView, android.view.View view, int i, long l) {
}
#Override
public boolean onGroupClick(ExpandableListView expandableListView, android.view.View view, int i, long l) {
return false;
}
#Override
public void setLoading(boolean isActive) {}
public void initViews(){
ela = new ExpandableListAdapter(this, categories);
elvListView = (ExpandableListView) findViewById(R.id.lv_preferences);
elvListView.setAdapter(ela);
elvListView.setOnItemClickListener(this);
elvListView.setOnGroupClickListener(this);
}
#Override
public void showGetPreferencesSuccess(List<CategoryModel> categories) {
setLoading(false);
mCategories = categories;
populateList();
initViews();
}
#Override
public void showGetPreferencesFail(int errorCode) {
}
#Override
public void setPresenter(PreferencesContract.Presenter presenter) {
mPresenterPreferences = Preconditions.checkNotNull(presenter);
}
}
Adapter is as follows:
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context context;
private ArrayList<String> item;
private ArrayList<Boolean> itemsChecked;
private ArrayList<ArrayList<Boolean>> childChecked;
private ArrayList<ArrayList<String>> childList;
public ExpandableListAdapter(Context c, ArrayList<CategoryModel> d) {
this.context = c;
this.item = new ArrayList<>();
for (int i = 0; i< d.size(); i++){
this.item.add(d.get(i).getCategoryName());
ArrayList<String> subCat = new ArrayList<>();
for (int j = 0 ; j < d.get(j).getSubCategories().size() ; j++){
subCat.add(d.get(j).getSubCategories().get(j).getSubCategoryName());
}
childList.add(subCat);
}
itemsChecked = new ArrayList<>();
childChecked = new ArrayList<ArrayList<Boolean>>();
for (int i = 0; i < this.item.size() ; i++) {
itemsChecked.add(false);
ArrayList <Boolean>temp = new ArrayList<>();
for (int j = 0 ; j < childList.get(i).size(); j ++){
temp.add(false);
}
childChecked.add(temp);
}
}
#Override
public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, final ViewGroup parent) {
LayoutInflater infalInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.my_preferences_list_group, null);
TextView tvName = (TextView) convertView.findViewById(R.id.tvGroupName);
final CheckBox checkBox = (CheckBox)convertView.findViewById(R.id.checkbox);
if((getChildrenCount(groupPosition) == 0 && itemsChecked.get(groupPosition))|| (getChildrenCount(groupPosition) > 0 && !(childChecked.get(groupPosition).contains(false)))) {
checkBox.setChecked(true);
}
else {
checkBox.setChecked(false);
}
checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CheckBox checkBox = (CheckBox)view;
RelativeLayout vwParentRow = (RelativeLayout)view.getParent();
TextView child = (TextView)vwParentRow.getChildAt(0);
final int position = item.indexOf(child.getText());
if (checkBox.isChecked()){
itemsChecked.set(position, true);
for (int i = 0 ; i < getChildrenCount(groupPosition); i++){
childChecked.get(groupPosition).set(i, true);
}
}
else {
itemsChecked.set(position, false);
for (int i = 0 ; i < getChildrenCount(groupPosition); i++){
childChecked.get(groupPosition).set(i, false);
}
}
ExpandableListAdapter.this.notifyDataSetChanged();
}
});
TextView tvCount = (TextView) convertView.findViewById(R.id.tv_item_count);
tvName.setText(item.get(groupPosition));
int childCount = getChildrenCount(groupPosition);
if (childCount > 0) {
tvCount.setText(getChildrenCount(groupPosition) + "items");
tvCount.setVisibility(View.VISIBLE);
}
if (isExpanded) {
}
else {
}
return convertView;
}
#Override
public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
LayoutInflater infalInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.my_preferences_list_item, null);
TextView tvName = (TextView) convertView.findViewById(R.id.tv_item);
CheckBox checkBox = (CheckBox)convertView.findViewById(R.id.checkBox);
if (childChecked.get(groupPosition).get(childPosition))
checkBox.setChecked(true);
checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CheckBox checkBox = (CheckBox)view;
RelativeLayout vwParentRow = (RelativeLayout)view.getParent();
TextView child = (TextView)vwParentRow.getChildAt(0);
int position = -1;
for (int i = 0 ; i < childList.size(); i++){
if (childList.get(i).contains(child.getText())){
if(checkBox.isChecked()) {
childChecked.get(i).set(childList.get(i).indexOf(child.getText()) , true);
ExpandableListAdapter.this.notifyDataSetChanged();
}
else {
childChecked.get(i).set(childList.get(i).indexOf(child.getText()) , false);
ExpandableListAdapter.this.notifyDataSetChanged();
}
}
}
if (checkBox.isChecked()){
if (position >0 )
itemsChecked.set(position, true);
}
else if(position > 0) {
itemsChecked.set(position, false);
}
}
});
String s = childList.get(groupPosition).get(childPosition);
tvName.setText(s);
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return childList.get(groupPosition).size();
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return childList.get(groupPosition).get(childPosition);
}
#Override
public int getGroupCount() {
return item.size();
}
#Override
public Object getGroup(int groupPosition) {
return item.get(groupPosition);
}
#Override
public long getGroupId(int groupPosition) {
return 0;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return 0;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
I have an idea of sending data from Activity to Adapter.
Any help in doing it some other way?
I think it's as simple as creating a getter inside your adapter
public List<String> getItems() {
return this.item;
}
And inside onOptionsItemSelected in the activity
ela.getItems();
public class MainActivity extends AppCompatActivity {
private CollapsingToolbarLayout collapsingToolbarLayout = null;
HashMap<String, List<ExpandableListItem>> _child;
String response;
String serviceName, serviceIcon, serviceId;
ExpandableListView expandableListView;
CustomExpandableListAdapter expandableListAdapter;
String groupName;
String childName;
List<ExpandableListItem> listtG1;
JSONArray jsonArray;
List<ExpandableListItem> _header;
ExpandableListItem rowData;
List<String> _groupNameList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
collapsingToolbarLayout.setTitle(getResources().getString(R.string.user_name));
new CategoryServices().execute("");
expandableListView = (ExpandableListView) findViewById(R.id.expandableListView);
expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
groupName = _groupNameList.get(groupPosition);
listtG1 = _child.get(groupName);
Log.d("ListSize", String.valueOf(listtG1.size()));
Toast.makeText(MainActivity.this,groupName+""+childName,Toast.LENGTH_LONG).show();
}
});
expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
Toast.makeText(MainActivity.this,groupName+""+childName,Toast.LENGTH_LONG).show();
}
});
expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
groupName = _groupNameList.get(groupPosition);
listtG1 = _child.get(groupName);
Toast.makeText(MainActivity.this, groupName,Toast.LENGTH_LONG).show();
Log.d("ListSize", String.valueOf(listtG1.size()));
if (listtG1.size() == 1 && listtG1.get(0).getServiceName().equals(groupName)) {
expandableListView.setGroupIndicator(null);
return true;
}
return false;
}
});
expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
childName = listtG1.get(childPosition).getServiceName();
Toast.makeText(
getApplicationContext(),
childName, Toast.LENGTH_SHORT
).show();
return false;
}
});
dynamicToolbarColor();
toolbarTextAppernce();
}
private void dynamicToolbarColor() {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.profile_pic);
Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
#Override
public void onGenerated(Palette palette) {
collapsingToolbarLayout.setContentScrimColor(palette.getMutedColor(R.attr.colorPrimary));
collapsingToolbarLayout.setStatusBarScrimColor(palette.getMutedColor(R.attr.colorPrimaryDark));
}
});
}
private void toolbarTextAppernce() {
collapsingToolbarLayout.setCollapsedTitleTextAppearance(R.style.collapsedappbar);
collapsingToolbarLayout.setExpandedTitleTextAppearance(R.style.expandedappbar);
}
class CategoryServices extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... params) {
response = JSONFunctions.getJSONfromURL("http://cpanel.smartindiaservice.com/api/categoryservices?categoryid=13");
return response;
}
#Override
protected void onPostExecute(String result) {
try {
setListAdapter(result, expandableListView);
// return false;
} catch (NullPointerException e) {
}
super.onPostExecute(result);
}
}
private void setListAdapter(String response, ExpandableListView expandableListView) {
_child = new HashMap<>();
_groupNameList = new ArrayList<>();
if (!response.isEmpty()) {
try {
jsonArray = new JSONArray(response);
if (jsonArray != null && jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject productObj = jsonArray.getJSONObject(i);
String groupName = productObj.getString("Service");
JSONArray servicesArray = productObj.getJSONArray("SubServices");
if (servicesArray != null && servicesArray.length() > 0) {
_header = new ArrayList<>();
for (int j = 0; j < servicesArray.length(); j++) {
JSONObject serviceObj = servicesArray.getJSONObject(j);
rowData = new ExpandableListItem();
serviceName = serviceObj.getString("SubServiceName");
serviceIcon = serviceObj.getString("SubServiceDescription");
serviceId = serviceObj.getString("SubServiceID");
rowData.setGroupName(groupName);
rowData.setServiceIcon(serviceIcon);
rowData.setServiceId(serviceId);
rowData.setServiceName(serviceName);
_header.add(rowData);
}
}
_child.put(groupName, _header);
_groupNameList.add(groupName);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
expandableListAdapter = new CustomExpandableListAdapter(this, _groupNameList, _child);
expandableListView.setAdapter(expandableListAdapter);
}
}
}
public class CustomExpandableListAdapter extends BaseExpandableListAdapter {
private Context context;
private List<String> expandableListTitle;
private HashMap<String, List<ExpandableListItem>> expandableListDetail;
public CustomExpandableListAdapter(Context context, List<String> expandableListTitle,
HashMap<String, List<ExpandableListItem>> expandableListDetail) {
this.context = context;
this.expandableListTitle = expandableListTitle;
this.expandableListDetail = expandableListDetail;
}
#Override
public Object getChild(int listPosition, int expandedListPosition) {
return this.expandableListDetail.get(this.expandableListTitle.get(listPosition))
.get(expandedListPosition);
}
#Override
public long getChildId(int listPosition, int expandedListPosition) {
return expandedListPosition;
}
#Override
public View getChildView(int listPosition, final int expandedListPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
// final String expandedListText = getChild(listPosition, expandedListPosition).g;
ExpandableListItem rowData = (ExpandableListItem) getChild(listPosition, expandedListPosition);
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.list_item, null);
}
TextView expandedListTextView = (TextView) convertView
.findViewById(R.id.expandedListItem);
expandedListTextView.setText(rowData.getServiceName());
return convertView;
}
#Override
public int getChildrenCount(int listPosition) {
return this.expandableListDetail.get(this.expandableListTitle.get(listPosition))
.size();
}
#Override
public Object getGroup(int listPosition) {
return this.expandableListTitle.get(listPosition);
}
#Override
public int getGroupCount() {
return this.expandableListTitle.size();
}
#Override
public long getGroupId(int listPosition) {
return listPosition;
}
#Override
public View getGroupView(int listPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String listTitle = (String) getGroup(listPosition);
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.list_group, null);
}
TextView listTitleTextView = (TextView) convertView
.findViewById(R.id.listTitle);
listTitleTextView.setTypeface(null, Typeface.BOLD);
listTitleTextView.setText(listTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int listPosition, int expandedListPosition) {
return true;
}
}
this is my activity and adapter i am able to display data in expandable list-view i want show indicator when group contain more than one child and i want hide group indicator when group contain only one child and group name and child name is same i am trying to in activity expandableListView.setGroupIndicator(null); using this code on setOnGroupClickListener this click but what happed firs time it display all indicator and when i click on group whose child is one and name same then it hide all indicator please suggest me how to fix this issue
Hey guys I am trying to get items on ExpandableListView's setOnGroupClickListener & setOnChildClickListener but not getting it's item.
Here is my code :
Group.java
public class Group {
private String Name;
private ArrayList<Child> Items;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public ArrayList<Child> getItems() {
return Items;
}
public void setItems(ArrayList<Child> items) {
Items = items;
}
}
Child.java
public class Child {
private String Name;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
}
ExpandListAdapter.java
public class ExpandListAdapter extends BaseExpandableListAdapter {
private Context context;
private ArrayList<Group> groups;
public ExpandListAdapter(Context context, ArrayList<Group> groups) {
this.context = context;
this.groups = groups;
}
#Override
public int getGroupCount() {
return groups.size();
}
#Override
public int getChildrenCount(int groupPosition) {
ArrayList<Child> chList = groups.get(groupPosition).getItems();
return chList.size();
}
#Override
public Object getGroup(int groupPosition) {
return groups.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
ArrayList<Child> chList = groups.get(groupPosition).getItems();
return chList.get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
Group group = (Group) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater inf = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView = inf.inflate(R.layout.group_item, null);
}
TextView tv = (TextView) convertView.findViewById(R.id.group_name);
tv.setText(group.getName());
return convertView;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
Child child = (Child) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context
.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.child_item, null);
}
TextView tv = (TextView) convertView.findViewById(R.id.country_name);
tv.setText(child.getName().toString());
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
String url = "http://ec2-52-40-135-171.us-west-2.compute.amazonaws.com/shop-cart/backend/web/api/category";
private ExpandListAdapter ExpAdapter;
private ExpandableListView ExpandList;
ArrayList<Group> list;
ArrayList<Child> ch_list;
Group gru;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ExpandList = (ExpandableListView) findViewById(R.id.exp_list);
list = new ArrayList<Group>();
makejsonobjreq();
ExpandList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
Toast.makeText(MainActivity.this, list.get(i) + "", Toast.LENGTH_SHORT).show();
return false;
}
});
ExpandList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i1, long l) {
Toast.makeText(MainActivity.this, "" + ExpAdapter.getChild(i, i1), Toast.LENGTH_SHORT).show();
return false;
}
});
}
private void makejsonobjreq() {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("RES", String.valueOf(response));
try {
JSONObject jo = response.getJSONObject("data");
Log.e("data RES", jo.toString());
Log.e("dataLENGTH", String.valueOf(jo.length()));
//CHNGE NEEDED ==> REPLACE 2 WITH jo.length();
for (int i = 0; i < 2; i++) {
gru = new Group();
gru.setName(jo.getJSONObject(String.valueOf(i + 1)).getJSONArray("parent").getJSONObject(0).getString("name"));
Log.e("gru", gru.getName());
ch_list = new ArrayList<Child>();
JSONArray ja = jo.getJSONObject(String.valueOf(i + 1)).getJSONArray("child");
Log.e("child ARRAY", String.valueOf(ja));
Log.e("child LENGTH", String.valueOf(ja.length()));
for (int j = 0; j < ja.length(); j++) {
Child ch = new Child();
ch.setName(ja.getJSONObject(j).getString("name"));
ch_list.add(ch);
Log.e("CHILD NAME", "VAL OF J " + j + " " + ja.getJSONObject(j).getString("name"));
}
gru.setItems(ch_list);
list.add(gru);
}
ExpAdapter = new ExpandListAdapter(MainActivity.this, list);
ExpandList.setAdapter(ExpAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonObjectRequest);
}
}
put your item into the view as a tag in getChildView or getGroupView like this:
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
Child child = (Child) getChild(groupPosition, childPosition);
// keep your code
// set item as a tag
convertView.setTag(child);
return convertView;
}
then you can get the item in the callback like
ExpandList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i1, long l) {
// get tag from view, it will be better if your check the object type.
Child child = (Child)view.getTag();
return false;
}
});
I've created a Spinner programmatically and add it to ListView's adapter. However, I can't get the Spinner back from ListView.
//listView = (NestedListView)findViewById(R.id.exListView);
create.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Spinner spinner;
for (int i=0; i<listView.getChildCount(); i++) {
if (listView.getChildAt(i) instanceof Spinner){
spinner = (Spinner) listView.getChildAt(i);
String selection = (String) spinner.getSelectedItem();
Log.e("spinner device", selection);
}
}
}
});
My adapter
public class ExpListAdapter extends BaseExpandableListAdapter {
private ArrayList<ArrayList<String>> mGroups;
private ArrayList<DeviceObject> deviceObList;
private ArrayList<RoomSuggestion> roObjList;
private Context mContext;
public ExpListAdapter (Context context,ArrayList<ArrayList<String>> groups, ArrayList<DeviceObject> deviceObList, ArrayList<RoomSuggestion> roObjList){
mContext = context;
mGroups = groups;
this.deviceObList = deviceObList;
this.roObjList = roObjList;
}
#Override
public int getGroupCount() {
return mGroups.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return mGroups.get(groupPosition).size();
}
#Override
public Object getGroup(int groupPosition) {
return mGroups.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return mGroups.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 true;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView,
ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.group_view, null);
}
if (isExpanded) {
//Изменяем что-нибудь, если текущая Group раскрыта
} else {
//Изменяем что-нибудь, если текущая Group скрыта
}
Typeface lightFace = Typeface.createFromAsset(mContext.getAssets(), "font/GothamProLight.ttf");
TextView textGroup = (TextView) convertView.findViewById(R.id.textGroup);
textGroup.setTypeface(lightFace);
textGroup.setText("Thereses gate 46");
return convertView;
}
#Override
public View getChildView(int groupPosition, final int childPosition, boolean isLastChild,
View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.child_view, null);
}
Typeface mediumFace = Typeface.createFromAsset(mContext.getAssets(), "font/GothamProMedium.ttf");
TextView textChild = (TextView) convertView.findViewById(R.id.textChild);
textChild.setTypeface(mediumFace);
textChild.setText( mGroups.get(groupPosition).get(childPosition) );
RelativeLayout rl = (RelativeLayout) convertView.findViewById(R.id.bg_button_screen);
if( !deviceObList.get(childPosition).getProduct_id().equals("0") ) {
rl.setBackgroundColor(Color.parseColor("#4fcc54"));
} else {
rl.setBackgroundColor(Color.parseColor("#e5910d"));
}
View linearLayoutG = convertView.findViewById(R.id.container);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(10, 0, 10, 30);
linearLayoutG.setLayoutParams(layoutParams);
RelativeLayout spinnerOpen = (RelativeLayout) convertView.findViewById(R.id.spinnerOpen);
View linearLayout = convertView.findViewById(R.id.spinnerL);
ImageView imageS = (ImageView)convertView.findViewById(R.id.spinnerImage);
imageS.getLayoutParams().width = 20;
imageS.getLayoutParams().height = 20;
imageS.setImageResource(R.drawable.spin_ok);
ArrayList<String> list = new ArrayList<String>();
for (int i=0; i<roObjList.size(); i++) {
list.add(roObjList.get(i).getName() );
}
final Spinner spinner = new Spinner(mContext);
// Make sure you have valid layout parameters.
spinner.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 100));
spinner.setBackgroundResource(R.drawable.bg_spinner);
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(mContext,
R.layout.spinner_item, list);
spinner.setAdapter(spinnerArrayAdapter);
// open spinner
spinnerOpen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
spinner.performClick();
}
});
((LinearLayout) linearLayout).addView(spinner);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.e("selected", String.valueOf(parent.getItemAtPosition(position)) );
Log.e("childPosition", String.valueOf(childPosition));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
You can try the following code:
//listView = (NestedListView)findViewById(R.id.exListView);
create.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(int i = 0; i < listView.getAdapter().getCount(); i++ ) {
for(int i = 0; i < listView.getChildCount(); i++ ) {
View _mainView = listView.getChildAt(i);
LinearLayout _linearLayout = _mainView.findViewById(R.id.spinnerL);
Spinner spinner = (Spinner) _linearLayout.getChildAt(0);
String selection = (String) spinner.getSelectedItem();
Log.e("spinner device", selection);
}
}
}
});