Hey people I'm Implementing TreeView using ExpandableListView. But I have some measure problem that I unfortunately can't solve it.
Here's ScreenShots of the problem:
You can see that there are problems in measuring. As long as I'm new to Android I don't really understand onMeasure() method.
I have 1 ExpandableListView and in it's getChildView() i return CustomExapndableListView-s.
Here's code:
ExpandableListAdapter :
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context context;
private List<String> listDataHeader;
private HashMap<String, List<String>> listDataChild;
public ExpandableListAdapter (Context context, List<String> listDataHeader, HashMap<String, List<String>> listChildData) {
this.context = context;
this.listDataHeader = listDataHeader;
this.listDataChild = listChildData;
}
#Override
public int getGroupCount() {
return this.listDataHeader.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return this.listDataChild.get(this.listDataHeader.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition) {
return this.listDataHeader.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return this.listDataChild.get(this.listDataHeader.get(groupPosition)).get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
Log.i("Header: ", " " + headerTitle);
if(convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
/*final String childText = (String) getChild(groupPosition, childPosition);
if(convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
}
TextView txtListChild = (TextView) convertView.findViewById(R.id.lblListItem);
txtListChild.setText(childText);*/
String childText = (String) getChild(groupPosition, childPosition);
if(listDataChild.containsKey(childText)){
Log.i("Child", "" + childText);
CustomExpandableListView explv = new CustomExpandableListView(context);
// explv.setRows(calculateRowCount((String)getGroup(groupPosition), null));
// ChildLayerExpandableListAdapter adapter = new ChildLayerExpandableListAdapter(context, listDataChild.get(getGroup(groupPosition)), listDataChild);
Log.i("Opaaaa:", " " + getGroup(groupPosition));
List<String> newHeaders = new ArrayList <String>();
newHeaders.add(childText);
// listDataChild.get(getGroup(groupPosition))
ExpandableListAdapter adapter = new ExpandableListAdapter(context, newHeaders, listDataChild);
explv.setAdapter(adapter);
explv.setGroupIndicator(null);
convertView = explv;
convertView.setPadding(20, 0, 0, 0);
}else{
// if(convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
// }
Log.i("Else:", " " + childText);
TextView txtListChild = (TextView) convertView.findViewById(R.id.lblListItem);
txtListChild.setText(childText);
convertView.setPadding(20, 0, 0, 0);
}
return convertView;
}
private int calculateRowCount (String key, ExpandableListView listView) {
int groupCount = listDataChild.get(key).size();
int rowCtr = 0;
for(int i = 0; i < groupCount; i++) {
rowCtr++;
if( (listView != null) && (listView.isGroupExpanded(i)))
rowCtr += listDataChild.get(listDataChild.get(key).get(i)).size() - 1;
}
return rowCtr;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
CustomExpandableListView :
public class CustomExpandableListView extends ExpandableListView {
private static final int HEIGHT = 20;
private int rows;
public void setRows(int rows) {
this.rows = rows;
}
public CustomExpandableListView(Context context) {
super(context);
}
public CustomExpandableListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
heightMeasureSpec = MeasureSpec.makeMeasureSpec(500, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// setMeasuredDimension(getMeasuredWidth(), rows * HEIGHT);
}
}
What I want to do is,when I expand the view, I want all children to be shown and I could just scroll down the ListView. Right now some children are hidden under different children.
Thanks in Advance for your Help.
#Code Word I'm sorry, I forgot to share my solution.
As I mentioned before I implemented treeView with ListView. Here is my source code.
TreeElementI.java :
public interface TreeElementI extends Serializable{
public void addChild(TreeElementI child);
public String getId();
public void setId(String id);
public String getOutlineTitle();
public void setOutlineTitle(String outlineTitle);
public boolean isHasParent();
public void setHasParent(boolean hasParent);
public boolean isHasChild();
public void setHasChild(boolean hasChild);
public int getLevel();
public void setLevel(int level);
public boolean isExpanded();
public void setExpanded(boolean expanded);
public ArrayList<TreeElementI> getChildList();
public TreeElementI getParent();
public void setParent(TreeElementI parent);
}
TreeElement.java :
public class TreeElement implements TreeElementI{
private String id;
private String outlineTitle;
private boolean hasParent;
private boolean hasChild;
private TreeElementI parent;
private int level;
private ArrayList<TreeElementI> childList;
private boolean expanded;
public TreeElement(String id, String outlineTitle) {
super();
this.childList = new ArrayList<TreeElementI>();
this.id = id;
this.outlineTitle = outlineTitle;
this.level = 0;
this.hasParent = true;
this.hasChild = false;
this.parent = null;
}
public TreeElement(String id, String outlineTitle, boolean hasParent, boolean hasChild, TreeElement parent, int level, boolean expanded) {
super();
this.childList = new ArrayList<TreeElementI>();
this.id = id;
this.outlineTitle = outlineTitle;
this.hasParent = hasParent;
this.hasChild = hasChild;
this.parent = parent;
if(parent != null) {
this.parent.getChildList().add(this);
}
this.level = level;
this.expanded = expanded;
}
#Override
public void addChild(TreeElementI child) {
this.getChildList().add(child);
this.setHasParent(false);
this.setHasChild(true);
child.setParent(this);
child.setLevel(this.getLevel() + 1);
}
#Override
public String getId() {
return this.id;
}
#Override
public void setId(String id) {
this.id = id;
}
#Override
public String getOutlineTitle() {
return this.outlineTitle;
}
#Override
public void setOutlineTitle(String outlineTitle) {
this.outlineTitle = outlineTitle;
}
#Override
public boolean isHasParent() {
return this.hasParent;
}
#Override
public void setHasParent(boolean hasParent) {
this.hasParent = hasParent;
}
#Override
public boolean isHasChild() {
return this.hasChild;
}
#Override
public void setHasChild(boolean hasChild) {
this.hasChild = hasChild;
}
#Override
public int getLevel() {
return this.level;
}
#Override
public void setLevel(int level) {
this.level = level;
}
#Override
public boolean isExpanded() {
return this.expanded;
}
#Override
public void setExpanded(boolean expanded) {
this.expanded = expanded;
}
#Override
public ArrayList<TreeElementI> getChildList() {
return this.childList;
}
#Override
public TreeElementI getParent() {
return this.parent;
}
#Override
public void setParent(TreeElementI parent) {
this.parent = parent;
}
}
TreeViewClassifAdapter.java :
public class TreeViewClassifAdapter extends BaseAdapter {
private static final int TREE_ELEMENT_PADDING_VAL = 25;
private List<TreeElementI> fileList;
private Context context;
private Bitmap iconCollapse;
private Bitmap iconExpand;
private Dialog dialog;
private EditText textLabel;
private XTreeViewClassif treeView;
public TreeViewClassifAdapter(Context context, List<TreeElementI> fileList, Dialog dialog, EditText textLabel, XTreeViewClassif treeView) {
this.context = context;
this.fileList = fileList;
this.dialog = dialog;
this.textLabel = textLabel;
this.treeView = treeView;
iconCollapse = BitmapFactory.decodeResource(context.getResources(), R.drawable.x_treeview_outline_list_collapse);
iconExpand = BitmapFactory.decodeResource(context.getResources(), R.drawable.x_treeview_outline_list_expand);
}
public List<TreeElementI> getListData() {
return this.fileList;
}
#Override
public int getCount() {
return this.fileList.size();
}
#Override
public Object getItem(int position) {
return this.fileList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
convertView = View.inflate(context, R.layout.x_treeview_classif_list_item, null);
holder = new ViewHolder();
holder.setTextView((TextView) convertView.findViewById(R.id.text));
holder.setImageView((ImageView) convertView.findViewById(R.id.icon));
convertView.setTag(holder);
final TreeElementI elem = (TreeElementI) getItem(position);
int level = elem.getLevel();
holder.getIcon().setPadding(TREE_ELEMENT_PADDING_VAL * (level + 1), holder.icon.getPaddingTop(), 0, holder.icon.getPaddingBottom());
holder.getText().setText(elem.getOutlineTitle());
if (elem.isHasChild() && (elem.isExpanded() == false)) {
holder.getIcon().setImageBitmap(iconCollapse);
} else if (elem.isHasChild() && (elem.isExpanded() == true)) {
holder.getIcon().setImageBitmap(iconExpand);
} else if (!elem.isHasChild()) {
holder.getIcon().setImageBitmap(iconCollapse);
holder.getIcon().setVisibility(View.INVISIBLE);
}
IconClickListener iconListener = new IconClickListener(this, position);
TextClickListener txtListener = new TextClickListener((ArrayList<TreeElementI>) this.getListData(), position);
holder.getIcon().setOnClickListener(iconListener);
holder.getText().setOnClickListener(txtListener);
return convertView;
}
private class ViewHolder {
ImageView icon;
TextView text;
public TextView getText() {
return this.text;
}
public void setTextView(TextView text) {
this.text = text;
}
public ImageView getIcon() {
return this.icon;
}
public void setImageView(ImageView icon) {
this.icon = icon;
}
}
/**
* Listener For TreeElement Text Click
*/
private class TextClickListener implements View.OnClickListener {
private ArrayList<TreeElementI> list;
private int position;
public TextClickListener(ArrayList<TreeElementI> list, int position) {
this.list = list;
this.position = position;
}
#Override
public void onClick(View v) {
treeView.setXValue(String.valueOf(list.get(position).getId()));
dialog.dismiss();
}
}
/**
* Listener for TreeElement "Expand" button Click
*/
private class IconClickListener implements View.OnClickListener {
private ArrayList<TreeElementI> list;
private TreeViewClassifAdapter adapter;
private int position;
public IconClickListener(TreeViewClassifAdapter adapter, int position) {
this.list = (ArrayList<TreeElementI>) adapter.getListData();
this.adapter = adapter;
this.position = position;
}
#Override
public void onClick(View v) {
if (!list.get(position).isHasChild()) {
return;
}
if (list.get(position).isExpanded()) {
list.get(position).setExpanded(false);
TreeElementI element = list.get(position);
ArrayList<TreeElementI> temp = new ArrayList<TreeElementI>();
for (int i = position + 1; i < list.size(); i++) {
if (element.getLevel() >= list.get(i).getLevel()) {
break;
}
temp.add(list.get(i));
}
list.removeAll(temp);
adapter.notifyDataSetChanged();
} else {
TreeElementI obj = list.get(position);
obj.setExpanded(true);
int level = obj.getLevel();
int nextLevel = level + 1;
for (TreeElementI element : obj.getChildList()) {
element.setLevel(nextLevel);
element.setExpanded(false);
list.add(position + 1, element);
}
adapter.notifyDataSetChanged();
}
}
}
}
I hope it's not too late and this source code will help you.
Related
Problem: When I click on Custom/Random nothing is happening.
(please see screenshot below).
I implemented ExpandListView successfull using this example, but in my case data is coming from database, that is only difference. I debug my code, it is going inside expandAll() and when I run application, it is bydefault came with expanded list.
Screenshot of my current code, actually, I impl expandeListview in dialog box and inflate row using expandlistadapter
My code:
ExpandableCategoryAdapter:
public class ExpandableCategoryAdapter extends BaseExpandableListAdapter {
private static final String TAG = ExpandableCategoryAdapter.class.getSimpleName();
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
private Context context;
private List<CategoryHeader> originalList;
private List<CategoryHeader> headerList;
private HamburgerMenuListener menuInterface;
public ExpandableCategoryAdapter(Context context, List<CategoryHeader> generalList, HamburgerMenuListener menuInterface) {
this.context = context;
this.headerList = generalList;
this.originalList = generalList;
this.menuInterface = menuInterface;
}
private boolean isPositionHeader(int position) {
return position == 0 || position == 6;
}
private CategoryHeader getItem(int position) {
return originalList.get(position);
}
private void showLog(String msg) {
Log.d(TAG, msg);
}
#Override
public int getGroupCount() {
return headerList.size();
}
#Override
public int getChildrenCount(int groupPosition) {
List<CustomCategory> countryList = headerList.get(groupPosition).getCategoryList();
return countryList.size();
}
#Override
public Object getGroup(int groupPosition) {
return headerList.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
List<CustomCategory> countryList = headerList.get(groupPosition).getCategoryList();
return countryList.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 view, ViewGroup parent) {
CategoryHeader categoryHeader = (CategoryHeader) getGroup(groupPosition);
if (view == null) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.row_custom_category_list, null);
}
TextView heading = view.findViewById(R.id.header_view);
heading.setText(categoryHeader.getHeaderName().trim());
return view;
}
public void filterData(String query) {
query = query.toLowerCase();
headerList.clear();
if (query.isEmpty()) {
headerList.addAll(originalList);
} else {
for (CategoryHeader categoryHeader : originalList) {
List<CustomCategory> countryList = categoryHeader.getCategoryList();
List<CustomCategory> newList = new ArrayList<CustomCategory>();
for (CustomCategory customCategory : countryList) {
if (customCategory.getName().toLowerCase().contains(query)) {
newList.add(customCategory);
}
}
if (newList.size() > 0) {
CategoryHeader nContinent = new CategoryHeader(categoryHeader.getHeaderName(), newList);
headerList.add(nContinent);
}
}
}
notifyDataSetChanged();
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
CustomCategory customCategory = (CustomCategory) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.row_general_list, null);
}
TextView name = convertView.findViewById(R.id.tv_category_item);
if (customCategory != null && customCategory.getName() != null) {
name.setText(customCategory.getName().trim());
}
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public class MyViewHolderItem extends RecyclerView.ViewHolder {
private TextView textViewItem;
private ImageView imageViewIcon;
private ImageView hamburgerMenu;
private Button customImageViewIcon;
public MyViewHolderItem(View itemView) {
super(itemView);
textViewItem = itemView.findViewById(R.id.tv_category_item);
imageViewIcon = itemView.findViewById(R.id.iv_category_icon);
customImageViewIcon = itemView.findViewById(R.id.iv_custom_category_icon);
hamburgerMenu = itemView.findViewById(R.id.hamburger_menu);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// menuInterface.onClickListItem(originalList.get(getAdapterPosition()).getCustCategoryId());
}
});
hamburgerMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (menuInterface != null) {
// menuInterface.onClickHamburger(originalList.get(getAdapterPosition()).getCustCategoryId());
}
}
});
}
}
public class MyViewHolderHeader extends RecyclerView.ViewHolder {
private TextView headerView;
public MyViewHolderHeader(View itemView) {
super(itemView);
headerView = itemView.findViewById(R.id.header_view);
}
}
}
CategoryDialog:
public class CategoryDialog extends BaseClass implements View.OnClickListener, Callback<String>, HamburgerMenuListener, ResultListener, SearchView.OnQueryTextListener, SearchView.OnCloseListener {
private static final String TAG = CategoryDialog.class.getSimpleName();
int i = 0;
private String landlineName, getProviderName, defaultName = "", phoneNum, customCategoryName, selected = "", getConsumerNum, getAccountNum, getOwnerName;
private long tempId = 0, categoryId, getCustomCategoryId, providerId, customCategoryId = 0, subProviderId;
private boolean stop = true, insurance, isEditPayment = false, isDeletedSQLite = false, isDeletedServer = false, isClicked = false;
private ExpandableCategoryAdapter expandableCategoryAdapter;
private List<CustomCategory> categories, customCategories;
private RecyclerView dialogRecyclerView;
private ExpandableListView expandableListView;
private DatabaseAdapter dbAdapter;
private Context context;
private SharedPreferences profilePreference;
private View promptsView;
private FloatingActionButton fab;
private CustomCategory customCategory;
private List<Reminder> dialogListItems;
private ImageView info;
private DialogListAdapter dialogListAdapter;
private Activity activity;
private ProviderDialog providerDialog;
private TextView inputInsuranceProvider, textViewError, inputBillProvider, errorView, information, subProviderError, providerError, customProviderError, consumerError, ownerError;
private EditText userInput, inputConsumerNumber, name, inputAccountNumber, inputCustomProvider;
private ProvidersInfo providersInfo;
private AlertDialog informationDialog, mDialog;
private CategoryListener categoryListener;
private General provider, subProvider;
private RelativeLayout relativeProvider, subProviderLayout, accountLayout, customLayout;
private LinearLayout spinnerLayout;
private List<General> mainInsuranceList = new ArrayList<>();
private CustomSpinnerAdapter spinnerAdapter;
private CustomSpinnerClass spinInsuranceList;
private ArrayList<CategoryHeader> headerArrayList = new ArrayList<CategoryHeader>();
private CategoryHeader categoryHeader;
public CategoryDialog(Context context, Activity activity) {
super(context, activity);
this.activity = activity;
this.context = context;
}
private void init() {
categories = new ArrayList<>();
customCategories = new ArrayList<>();
dbAdapter = RemindMe.getInstance().adapter;
dialogListItems = new ArrayList<>();
profilePreference = context.getSharedPreferences(PROFILE, MODE_PRIVATE);
providerDialog = new ProviderDialog(context);
providerDialog.setResultListener(this);
getDataFromSharedPref();
}
private void loadSomeData() {
categoryHeader = new CategoryHeader("Custom", customCategories);
headerArrayList.add(categoryHeader);
categoryHeader = new CategoryHeader("Random", categories);
headerArrayList.add(categoryHeader);
categoryHeader = new CategoryHeader("General", categories);
headerArrayList.add(categoryHeader);
}
public void setCategoryListener(CategoryListener listener) {
this.categoryListener = listener;
}
private void setClickListener() {
fab.setOnClickListener(this);
}
public void showCategoryDialog() {
LayoutInflater li = LayoutInflater.from(context);
promptsView = li.inflate(R.layout.row_category_dialog_layout, null);
init();
findViewById();
setClickListener();
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setView(promptsView);
alertDialogBuilder.setNegativeButton(context.getString(R.string.cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
recyclerView();
mDialog = alertDialogBuilder.create();
mDialog.setCancelable(false);
mDialog.getWindow().setBackgroundDrawableResource(R.color.colorWhite);
mDialog.show();
}
private void findViewById() {
expandableListView = promptsView.findViewById(R.id.expandableList);
fab = promptsView.findViewById(R.id.fab);
}
private void recyclerView() {
addToCategories();
loadSomeData();
showLog("headerArrayList: " + headerArrayList.size());
//expandableCategoryAdapter = new ExpandableCategoryAdapter(context, categories, this);
expandableCategoryAdapter = new ExpandableCategoryAdapter(context, headerArrayList, this);
// expandableListView.setHasFixedSize(true);
/* final LinearLayoutManager mLayoutManager;
mLayoutManager = new LinearLayoutManager(context);
expandableListView.setLayoutManager(mLayoutManager);
expandableListView.setItemAnimator(new DefaultItemAnimator());*/
try {
expandableListView.setAdapter(expandableCategoryAdapter);
} catch (Exception exp) {
exp.printStackTrace();
}
showLog("1");
expandAll();
listener();
// expandableCategoryAdapter.notifyDataSetChanged();
// expandableCategoryAdapter.refresh(headerArrayList);
}
private void listener() {
expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
for (int i = 0; i < headerArrayList.size(); i++) {
if (i != groupPosition) {
expandableListView.expandGroup(i);
}
}
}
});
}private void expandAll() {
showLog("2");
int count = expandableCategoryAdapter.getGroupCount();
showLog("3 :"+ count);
for (int i = 0; i < count; i++) {
showLog("4");
expandableListView.expandGroup(i);
}
}
public class Class******Adapter extends BaseExpandableListAdapter
{
private Context context;
private List<ModelClassObj> ModelClassObjs;
public ExpandableVocherDetailsAdapter(Context context,List<ModelClassObj>
ModelClassObjs)
{
this.context = context;
this.ModelClassObjs = ModelClassObjs;
}
public void refresh(List<ModelClassObj> ModelClassObjs)
{
this.ModelClassObjs = ModelClassObjs;
notifyDataSetChanged();
}
#Override
public boolean isChildSelectable(int i, int i1) {
return false;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public Object getChild(int i, int i1) {
return null;
}
#Override
public long getGroupId(int i) {
return 0;
}
#Override
public Object getGroup(int i) {
return null;
}
#Override
public long getChildId(int i, int i1) {
return 0;
}
#Override
public int getChildrenCount(int i) {
return 1;
}
#Override
public int getGroupCount() {
if(ModelClassObjs!=null && ModelClassObjs.size()>0)
return ModelClassObjs.size();
return 0;
}
#Override
public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup)
{
ModelClassObj obj = ModelClassObjs.get(i);
EditText tvCreatedBy,tvCreatedOn,tvDescription,tvVoucherNumber,tvcancelReason,tvcancelBy,tvCancelApproveBy,tvCancelApproveOn,tvdocph,tvdocemail;
LinearLayout tvCancelReasonHed,lldocph_email,llcancel_appro;
view = LayoutInflater.from(context).inflate(R.layout.exp_vocher_child,null);
tvCreatedBy = view.findViewById(R.id.tvCreatedBy);
tvCreatedBy.setText(obj.getCreatedBy());
return view;
}
#Override
public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup)
{
final ModelClassObj obj = ModelClassObjs.get(i);
TextView tvDoctorName,tvvpAmnt,tv_vp_payment,tv_vp_ReceipientType;
ImageView ivIndicator;
LinearLayout llParent;
view =
LayoutInflater.from(context).inflate(R.layout.exp_vocher_parent_cell,null);
tvDoctorName = view.findViewById(R.id.tvDoctorName);
tvDoctorName.setText(obj.getDoctorName());
if(b==true)
ivIndicator.setImageResource(R.drawable.up);
else
ivIndicator.setImageResource(R.drawable.down);
return view;
}
}
Activity Class
expandableLisView.setOnGroupExpandListener(new
ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
for (int i = 0; i < voucherDetailsObjs.size(); i++) {
if (i != groupPosition) {
exlvVocherDetail.collapseGroup(i);
}
}
}
});
I was also working on expandable list view, fortunately i got a great example for that
Link : https://github.com/sourabhgupta811/ExpandableRecyclerView
Following is the adapter layout file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="#dimen/cardview_default_elevation"
app:cardUseCompatPadding="true">
<TextView
android:id="#+id/head_textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingBottom="16dp"
android:paddingTop="16dp"
android:textAllCaps="true"
android:textSize="22sp"
tools:text="Tap to expand" />
</android.support.v7.widget.CardView>
<com.example.smoothcardanimation.ExpandableLinearLayout
android:id="#+id/expandableView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:expandDuration="500">
<TextView
android:id="#+id/expanded_textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:background="#android:color/darker_gray"
android:gravity="center"
android:padding="20dp"
android:paddingBottom="8dp"
android:paddingTop="8dp"
android:textAllCaps="true"
android:textSize="16sp"
tools:text="This is sample text" />
</com.example.smoothcardanimation.ExpandableLinearLayout>
Adapter File :
public class RecyclerViewAdapter extends
RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private List<ExpandModel> data;
private RecyclerView recyclerView;
private int lastExpandedCardPosition;
private int i=0;
public RecyclerViewAdapter(RecyclerView recyclerView) {
this.recyclerView = recyclerView;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View v = inflater.inflate(R.layout.card_item, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.headTextView.setText("Tap to expand");
holder.expandedTextView.setText("this is sample text");
if(data.get(position).isExpanded()){
holder.expandableView.setVisibility(View.VISIBLE);
holder.expandableView.setExpanded(true);
}
else{
holder.expandableView.setVisibility(View.GONE);
holder.expandableView.setExpanded(false);
}
}
#Override
public int getItemCount()
return data.size();
}
public void setData(List<ExpandModel> data) {
this.data = data;
}
public void addItem(int i) {
data.add(i,new ExpandModel());
if(i<=lastExpandedCardPosition)
lastExpandedCardPosition++;
notifyDataSetChanged();
}
public void deleteItem(int i) {
data.remove(i);
notifyDataSetChanged();
}
class ViewHolder extends RecyclerView.ViewHolder {
ExpandableLinearLayout expandableView;
TextView headTextView;
TextView expandedTextView;
ExpandListener expandListener = new ExpandListener() {
#Override
public void onExpandComplete() {
if(lastExpandedCardPosition!=getAdapterPosition() && recyclerView.findViewHolderForAdapterPosition(lastExpandedCardPosition)!=null){
((ExpandableLinearLayout)recyclerView.findViewHolderForAdapterPosition(lastExpandedCardPosition).itemView.findViewById(R.id.expandableView)).setExpanded(false);
data.get(lastExpandedCardPosition).setExpanded(false);
((ExpandableLinearLayout)recyclerView.findViewHolderForAdapterPosition(lastExpandedCardPosition).itemView.findViewById(R.id.expandableView)).toggle();
}
else if(lastExpandedCardPosition!=getAdapterPosition() && recyclerView.findViewHolderForAdapterPosition(lastExpandedCardPosition)==null){
data.get(lastExpandedCardPosition).setExpanded(false);
}
lastExpandedCardPosition = getAdapterPosition();
}
#Override
public void onCollapseComplete() {
}
};
ViewHolder(View itemView) {
super(itemView);
headTextView = itemView.findViewById(R.id.head_textview);
expandedTextView = itemView.findViewById(R.id.expanded_textview);
expandableView = itemView.findViewById(R.id.expandableView);
expandableView.setExpandListener(expandListener);
initializeClicks();
}
private void initializeClicks() {
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (expandableView.isExpanded()) {
expandableView.setExpanded(false);
expandableView.toggle();
data.get(getAdapterPosition()).setExpanded(false);
} else {
expandableView.setExpanded(true);
data.get(getAdapterPosition()).setExpanded(true);
expandableView.toggle();
}
}
});
}
}
}
Expandable View File :
public class ExpandableLinearLayout extends LinearLayout{
private boolean expanded;
private int duration;
private ExpandListener expandListener;
public ExpandableLinearLayout(Context context) {
super(context);
}
public ExpandableLinearLayout(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
public ExpandableLinearLayout(Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs);
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public ExpandableLinearLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(attrs);
}
private void init(AttributeSet attributeSet) {
TypedArray customValues = getContext().obtainStyledAttributes(attributeSet, R.styleable.ExpandableLinearLayout);
duration = customValues.getInt(R.styleable.ExpandableLinearLayout_expandDuration, -1);
customValues.recycle();
}
public boolean isExpanded() {
return expanded;
}
public void setExpanded(boolean expanded) {
Log.e("layout", expanded + "");
this.expanded = expanded;
}
public void toggle() {
if (expanded)
expandView(this);
else
hideView(this);
}
private void expandView(final View view) {
view.measure(WindowManager.LayoutParams.MATCH_PARENT
, View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
final int targetHeight = view.getMeasuredHeight();
// Older versions of android (pre API 21) cancel animations for views with a height of 0.
view.getLayoutParams().height = 1;
view.setVisibility(View.VISIBLE);
Animation a = new Animation() {
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
view.getLayoutParams().height = interpolatedTime == 1
? targetHeight : (int) (targetHeight * interpolatedTime);
view.requestLayout();
}
#Override
public boolean willChangeBounds() {
return true;
}
};
a.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
expandListener.onExpandComplete();
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
if (duration == -1)
a.setDuration((int) (targetHeight / view.getContext().getResources().getDisplayMetrics().density * 1.5));
else
a.setDuration(duration);
view.startAnimation(a);
}
private void hideView(final View view) {
final int initialHeight = view.getMeasuredHeight();
Animation a = new Animation() {
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
if (interpolatedTime == 1) {
view.setVisibility(View.GONE);
} else {
view.getLayoutParams().height = initialHeight - (int) (initialHeight * interpolatedTime);
view.requestLayout();
}
}
#Override
public boolean willChangeBounds() {
return true;
}
};
if (duration == -1)
a.setDuration((int) (initialHeight / view.getContext().getResources().getDisplayMetrics().density * 1.5));
else
a.setDuration(duration);
a.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
expandListener.onCollapseComplete();
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
view.startAnimation(a);
}
public void setExpandListener(ExpandListener expandListener) {
this.expandListener = expandListener;
}
}
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++)
[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;
}
I'm writing filter in Android and want to use BaseExpandableListAdapter with checkboxes. In my situation if the group elements have any child elements, may select group element too. Also all child elements may selected. Offer screenshot:
enter image description here
When i open dialog and select neccessary elements, then its selected elements put to text edittext. My problem in this, when i reopen dialog and close/open group elements my selected checkboxes changes. I can't find solution how to remember choices, when reopen dialog.
All my neccessary code offer following:
My entity class:
public class Category implements Listable, Parcelable{
private int id;
private String title;
private String c_date;
private List<Category> sub_categories = new ArrayList<>();
private boolean isChecked;
private int parent;
protected Category(Parcel in) {
id = in.readInt();
title = in.readString();
c_date = in.readString();
sub_categories = in.createTypedArrayList(Category.CREATOR);
isChecked = in.readByte() != 0;
parent = in.readInt();
m_date = in.readString();
}
public static final Creator<Category> CREATOR = new Creator<Category>() {
#Override
public Category createFromParcel(Parcel in) {
return new Category(in);
}
#Override
public Category[] newArray(int size) {
return new Category[size];
}
};
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(id);
parcel.writeString(title);
parcel.writeString(c_date);
parcel.writeTypedList(sub_categories);
parcel.writeByte((byte) (isChecked ? 1 : 0));
parcel.writeInt(parent);
parcel.writeString(m_date);
}
//getters, setters
}
My adapter class:
public class CategoryAdapter extends BaseExpandableListAdapter {
private Context context;
private ArrayList<Category> categories;
private LayoutInflater inflater;
public CategoryAdapter(Context context,
ArrayList<Category> categoryList) {
this.context = context;
this.categories = categoryList;
inflater = LayoutInflater.from(context);
}
public Object getChild(int groupPosition, int childPosition) {
return categories.get(groupPosition).getSub_categories().get(childPosition);
}
public long getChildId(int groupPosition, int childPosition) {
return (long)( groupPosition*1024+childPosition ); // Max 1024 children per group
}
private static class ViewHolder {
private TextView title;
private CheckBox cb;
}
public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder viewHolder;
boolean isChecked = categories.get(groupPosition).getSub_categories().get(childPosition).isChecked();
if (v != null)
viewHolder = (ViewHolder) v.getTag();
else {
v = inflater.inflate(R.layout.category_child_row, parent, false);
viewHolder = new ViewHolder();
viewHolder.title = (TextView)v.findViewById(R.id.title);
viewHolder.cb = (CheckBox)v.findViewById(R.id.check);
viewHolder.cb.setChecked(isChecked);
viewHolder.cb.setOnCheckedChangeListener(new CheckchangeChildListener(groupPosition, childPosition));
v.setTag(viewHolder);
}
final Category c = (Category) getChild( groupPosition, childPosition );
viewHolder.title.setText(c.getTitle());
return v;
}
class CheckchangeChildListener implements CompoundButton.OnCheckedChangeListener {
private int position;
private int childPosition;
public CheckchangeChildListener(int position, int childPosition) {
this.position= position;
this.childPosition = childPosition;
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if (isChecked) {
categories.get(position).getSub_categories().get(childPosition).setChecked(true);
} else {
categories.get(position).getSub_categories().get(childPosition).setChecked(false);
}
}
}
public int getChildrenCount(int groupPosition) {
return categories.get(groupPosition).getSub_categories().size();
}
public Object getGroup(int groupPosition) {
return categories.get( groupPosition );
}
public int getGroupCount() {
return categories.size();
}
public long getGroupId(int groupPosition) {
return (long)( groupPosition*1024 ); // To be consistent with getChildId
}
private static class ViewGroupHolder {
private TextView title;
private CheckBox cb;
private ImageView image;
}
public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
View v = convertView;
ViewGroupHolder holder;
boolean isChecked = categories.get(groupPosition).isChecked();
if(v != null)
holder = (ViewGroupHolder)v.getTag();
else {
v = inflater.inflate(R.layout.category_parent_row, parent, false);
holder = new ViewGroupHolder();
holder.title = (TextView)v.findViewById(R.id.title);
holder.cb = (CheckBox)v.findViewById(R.id.check);
holder.cb.setChecked(isChecked);
holder.image = (ImageView)v.findViewById(R.id.arrow);
holder.cb.setOnCheckedChangeListener(new CheckchangeGroupListener(groupPosition));
v.setTag(holder);
}
final Category category = (Category)getGroup(groupPosition);
holder.title.setText(category.getTitle());
if(getChildrenCount(groupPosition) == 0){
holder.cb.setVisibility(View.VISIBLE);
holder.image.setVisibility(View.INVISIBLE);
} else {
holder.image.setVisibility(View.VISIBLE);
holder.cb.setVisibility(View.INVISIBLE);
holder.image.setImageResource(isExpanded ? R.drawable.ic_chevron_down : R.drawable.ic_chevron_right);
}
return v;
}
class CheckchangeGroupListener implements CompoundButton.OnCheckedChangeListener {
private int position;
public CheckchangeGroupListener(int position) {
this.position= position;
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if (isChecked) {
categories.get(position).setChecked(true);
} else {
categories.get(position).setChecked(false);
}
}
}
public boolean hasStableIds() {
return true;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public void onGroupCollapsed (int groupPosition) {}
public void onGroupExpanded(int groupPosition) {}
public ArrayList<Category> getSelectedCats(){
ArrayList<Category> checkedCategories = new ArrayList<>();
for(Category c: categories){
if(c.isChecked()) checkedCategories.add(c);
if(!c.getSub_categories().isEmpty()){
for(Category category: c.getSub_categories()) {
if (category.isChecked()) checkedCategories.add(category);
}
}
}
return checkedCategories;
}
}
My custom EditText:
public class CategoryEditText<T extends Listable> extends EditText {
List<T> mItems;
String[] mListableItems;
CharSequence mHint;
OnItemSelectedListener<T> onItemSelectedListener;
DialogFragment newFragment;
public CategoryEditText(Context context) {
super(context);
mHint = getHint();
}
public CategoryEditText(Context context, AttributeSet attrs) {
super(context, attrs);
mHint = getHint();
}
public CategoryEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mHint = getHint();
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public CategoryEditText(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
mHint = getHint();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
setFocusable(false);
setClickable(true);
}
public void setItems(List<T> items) {
this.mItems = items;
newFragment = CategoryDialogFragment.newInstance((ArrayList<Category>)mItems, this);
this.mListableItems = new String[items.size()];
int i = 0;
for (T item : mItems) {
mListableItems[i++] = item.getLabel();
}
configureOnClickListener();
}
private void configureOnClickListener() {
setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Context context = getContext();
FragmentManager fm = ((Activity) context).getFragmentManager();
newFragment.show(fm, "dialog");
}
});
}
public void setOnItemSelectedListener(OnItemSelectedListener<T> onItemSelectedListener) {
this.onItemSelectedListener = onItemSelectedListener;
}
public interface OnItemSelectedListener<T> {
void onItemSelectedListener(T item, int selectedIndex);
}
}
My custom dialogfragment to display list:
public class CategoryDialogFragment extends DialogFragment {
ArrayList<Category> categories;
static EditText editText;
public static CategoryDialogFragment newInstance(ArrayList<Category> categories, EditText customEditText) {
CategoryDialogFragment frag = new CategoryDialogFragment();
Bundle args = new Bundle();
args.putParcelableArrayList("categories", categories);
frag.setArguments(args);
editText = customEditText;
return frag;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
categories = getArguments().getParcelableArrayList("categories");
View v = LayoutInflater.from(getActivity()).inflate(R.layout.select_category_layout, null);
ExpandableListView expandableListView = (ExpandableListView) v.findViewById(R.id.list);
final CategoryAdapter categoryAdapter = new CategoryAdapter(getActivity(), categories);
expandableListView.setAdapter(categoryAdapter);
MaterialDialog dialog = new MaterialDialog.Builder(getActivity())
.title(R.string.shop_category)
.customView(v, false)
.positiveText(R.string.select)
.negativeText(android.R.string.cancel)
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog materialDialog, #NonNull DialogAction dialogAction) {
ArrayList<Category> cats = categoryAdapter.getSelectedCats();
String selectedText = "";
for(int i=0; i<cats.size(); i++){
selectedText += cats.get(i).getTitle();
if(i+1 < cats.size()){
selectedText += " | ";
}
}
editText.setText(selectedText);
materialDialog.dismiss();
}
})
.build();
return dialog;
}
}
I tried to reading on the net about that but I didn`t find how to solve my problem.
The problem is your getView() method. I'd suggest reading up on how to correctly write a list adapter class.
private static class ViewHolder {
private TextView title;
private ChecBbox cb;
}
public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
boolean isChecked = categories.get(groupPosition).getSub_categories().get(childPosition).isChecked();
if( convertView != null )
viewHolder = (ViewHolder) v.getTag();
else {
v = inflater.inflate(R.layout.category_child_row, parent, false);
viewHolder = new ViewHolder();
holder.title = (TextView)v.findViewById(R.id.title);
holder.cb = (CheckBox)v.findViewById(R.id.check);
holder.cb.setChecked(isChecked);
cb.setOnCheckedChangeListener(new CheckchangeChildListener(groupPosition, childPosition));
v.setTag(viewHolder);
}
final Category c = (Category) getChild( groupPosition, childPosition );
title.setText(c.getTitle());
return v;
}
Checked changed listener:
class CheckchangeGroupListener implements CompoundButton.OnCheckedChangeListener {
private int groupPosition, childPosition;
public CheckchangeGroupListener(int groupPosition, int childPosition) {
this.groupPosition= groupPosition;
this.childPosition = childPosition;
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if (isChecked) {
categories.get(groupPosition).getSub_categories().get(childPosition).setChecked(true);
} else {
categories.get(groupPosition).getSub_categories().get(childPosition).setChecked(false);
}
}
I have a expandableListView and tried to change its childs like that:
((SubItem) adapter.getChild(i+1, 5)).setCount(unreadBox);
adapter.notifyDataSetChanged();
Here is my adapter class:
public class DrawerAdapter extends BaseExpandableListAdapter {
private Context context;
private List<Item> items;
private List<List<SubItem>> subItems;
public DrawerAdapter(Context context, List<Item> items, List<List<SubItem>> subItems) {
this.context = context;
this.items = items;
this.subItems = subItems;
}
#Override
public int getGroupCount() {
return items.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return subItems.get(groupPosition).size();
}
#Override
public Object getGroup(int position) {
return items.get(position);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return subItems.get(groupPosition).get(childPosition);
}
#Override
public long getGroupId(int position) {
return position;
}
#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 view, ViewGroup viewGroup) {
Item item = (Item) getGroup(groupPosition);
if (view == null) {
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.list_drawer_group, null);
}
ImageView iconView = (ImageView) view.findViewById(R.id.icon_view);
if (item.iconDrawableId != null) {
iconView.setImageResource(item.iconDrawableId);
iconView.setVisibility(View.VISIBLE);
} else {
iconView.setVisibility(View.GONE);
}
TextView groupHeader = (TextView) view.findViewById(R.id.group_header);
groupHeader.setText(item.title);
if (item.iconDrawableId != null) {
groupHeader.setPadding(
DimensionHelper.dpToPixels(context, 4.0f), 0,
DimensionHelper.dpToPixels(context, 16.0f), 0);
} else {
groupHeader.setPadding(
DimensionHelper.dpToPixels(context, 16.0f), 0,
DimensionHelper.dpToPixels(context, 16.0f), 0);
}
ImageView imageView = (ImageView) view.findViewById(R.id.image_view);
imageView.setImageResource(isExpanded ? R.drawable.ic_navigation_collapse : R.drawable.ic_navigation_expand);
imageView.setVisibility(getChildrenCount(groupPosition) > 0 ? View.VISIBLE : View.GONE);
return view;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isExpanded, View view, ViewGroup viewGroup) {
SubItem subItem = (SubItem) getChild(groupPosition, childPosition);
if (view == null) {
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.list_drawer_item, null);
}
TextView colorPreView = (TextView) view.findViewById(R.id.colorPreView);
if (subItem.getColor() != -1) {
colorPreView.setBackgroundColor(subItem.getColor());
colorPreView.setVisibility(View.VISIBLE);
} else {
colorPreView.setVisibility(View.GONE);
}
ImageView iconView = (ImageView) view.findViewById(R.id.icon_view);
if (subItem.iconDrawableId != null) {
iconView.setImageResource(subItem.iconDrawableId);
iconView.setVisibility(View.VISIBLE);
} else {
iconView.setVisibility(View.GONE);
}
TextView title = (TextView) view.findViewById(R.id.title_text_view);
title.setText(subItem.title);
if (subItem.iconDrawableId != null) {
title.setPadding(
DimensionHelper.dpToPixels(context, 4.0f), 0,
DimensionHelper.dpToPixels(context, 16.0f), 0);
} else {
title.setPadding(
DimensionHelper.dpToPixels(context, 40.0f), 0,
DimensionHelper.dpToPixels(context, 16.0f), 0);
}
TextView counter = (TextView) view.findViewById(R.id.counter_text_view);
counter.setText(String.valueOf(subItem.count));
counter.setVisibility(subItem.count > 0 ? View.VISIBLE : View.GONE);
return view;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public static class Item {
protected String title;
protected Integer iconDrawableId;
protected Listener listener;
public Item(String title, Integer iconDrawableId, Listener listener) {
this.title = title;
this.iconDrawableId = iconDrawableId;
this.listener = listener;
}
public Listener getListener() {
return listener;
}
public static interface Listener {
public void onClick(FragmentManager fragmentManager);
}
}
public static class SubItem extends Item {
protected long count;
protected int color;
public SubItem(String title, Integer iconDrawableId, long count, int color, Listener listener) {
super(title, iconDrawableId, listener);
this.count = count;
this.color = color;
}
public long getCount() {
return count;
}
public void setCount(long count) {
this.count = count;
}
public int getColor() {
return color;
}
public void setColor(int color) {
this.color = color;
}
}
}
notifyDataSetChanged() method is not working properly, sometimes getChildView is being called sometimes not,please help in order to fix this issue.
You are changing value to child Item however not setting back inside of Adapter.
SubItem item = ((SubItem) adapter.getChild(i+1, 5)).setCount(unreadBox);
adapter.setChild(i+1,5,item);
adapter.notifyDataSetChanged();
add this in Adapter
#Override
public void setChild(int groupPosition, int childPosition,SubItem item) {
subItems.get(groupPosition).get(childPosition) = item;
}