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;
}
}
Related
I have RecyclerView and there is a problem with that but inside extends BaseAdapter listview shows only the first element of data, after taking the only first item, the adapter does not go on putting data.
public class AdapterCorporationPrivilegeDescriptions extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<ModelPrivilegeDescription> itemList;
private ListPrivilegeParentListener parentListener;
private Context context;
private AdapterCorporationPrivilegeDescriptionnn adapter;
private boolean visibility;
private int width;
public AdapterCorporationPrivilegeDescriptions(Context context,
int width,
List<ModelPrivilegeDescription> itemList,
ListPrivilegeParentListener parentListener) {
this.itemList = itemList;
this.width = width;
this.parentListener = parentListener;
this.context = context;
}
public void setData(List<ModelPrivilegeDescription> itemList) {
this.itemList = itemList;
notifyDataSetChanged();
}
public void setVisibilityListView(boolean visibility) {
this.visibility = visibility;
}
#Override
public AdapterCorporationPrivilegeDescriptions.AdapterCorporationPrivilegeListHolder
onCreateViewHolder(ViewGroup parent, int viewType) {
return new AdapterCorporationPrivilegeDescriptions.AdapterCorporationPrivilegeListHolder(
LayoutInflater.from(parent.getContext()).inflate(
R.layout.item_corporation_privilege_descriptions, parent, false));
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
((AdapterCorporationPrivilegeDescriptions.AdapterCorporationPrivilegeListHolder) holder).setData(itemList.get(position));
}
#Override
public int getItemCount() {
return itemList == null ? 0 : itemList.size();
}
private class AdapterCorporationPrivilegeListHolder extends RecyclerView.ViewHolder {
private HTextView text;
private HImageView icon;
private HSwipeableListView listView;
private AdapterCorporationPrivilegeListHolder(View itemView) {
super(itemView);
text = itemView.findViewById(R.id.itemCorporationPrivilegeDescriptionsText);
icon = itemView.findViewById(R.id.itemCorporationPrivilegeDescriptionsIcon);
listView = itemView.findViewById(R.id.itemCorporationPrivilegeDescriptionsListView);
}
private SwipeMenuItem getDeleteItem() {
SwipeMenuItem swipeMenuItem = new SwipeMenuItem(context);
swipeMenuItem.setWidth(width);
swipeMenuItem.setBackground(R.color.red_delete);
swipeMenuItem.setIcon(R.drawable.ic_delete);
swipeMenuItem.setTitle(App.getStrWithId(R.string.payment_transfer_delete_button));
swipeMenuItem.setTitleColor(Color.WHITE);
swipeMenuItem.setTitleSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16, context.getResources().getDisplayMetrics()));
return swipeMenuItem;
}
HSwipeableListView.OnMenuItemClickListener onMenuItemClickListener = new HSwipeableListView.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(final int position, SwipeMenu menu, int index) {
if (index == 0) {
App.getInstance().getBusInstance().post(new CorporationPrivilegeDescriptionEvent(position));
}
return false;
}
};
public void setData(final ModelPrivilegeDescription data) {
SwipeMenuCreator creator = new SwipeMenuCreator() {
#Override
public void create(SwipeMenu menu) {
menu.addMenuItem(getDeleteItem());
}
};
listView.setDividerHeight(0);
listView.setMenuCreator(creator);
listView.setOnMenuItemClickListener(onMenuItemClickListener);
listView.setSwipeEnabled(!App.getInstance().isTalkBackEnabled());
//listView.setVisibility(visibility ? View.VISIBLE : View.GONE);
text.setText(data.transactionName);
if (data.innerList != null && !data.innerList.isEmpty()) {
AdapterCorporationPrivilegeDescriptionnn adapter = new AdapterCorporationPrivilegeDescriptionnn(context, data.innerList, childListener);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
} else {
listView.setVisibility(View.GONE);
icon.setVisibility(View.INVISIBLE);
}
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
float positionClosed = 0, positionOpened = 180;
if (listView.getVisibility() == View.VISIBLE) {
parentListener.onItemSelected(data);
listView.setVisibility(View.GONE);
icon.setRotation(positionClosed);
} else {
listView.setVisibility(View.VISIBLE);
icon.setRotation(positionOpened);
}
}
});
}
private final AdapterCorporationPrivilegeDescriptionnn.CorporationPrivilegeDescriptionListener childListener = new AdapterCorporationPrivilegeDescriptionnn.CorporationPrivilegeDescriptionListener() {
#Override
public void onLimitButtonClick(ModelPrivilegeDescriptionAccount item) {
int a = 5;
}
#Override
public void onDetailButtonClick(ModelPrivilegeDescriptionAccount item) {
int a = 5;
}
};
}
}
AdapterCorporationPrivilegeDescriptionnn issue in this class
public class AdapterCorporationPrivilegeDescriptionnn extends BaseAdapter {
private int RESOURCE_ID = R.layout.item_corporation_privilege_description;
private LayoutInflater inflater;
private List<ModelPrivilegeDescriptionAccount> list;
private CorporationPrivilegeDescriptionListener listener;
public AdapterCorporationPrivilegeDescriptionnn(Context context,
List<ModelPrivilegeDescriptionAccount> items,
CorporationPrivilegeDescriptionListener listener) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
list = items;
this.listener = listener;
}
#Override
public int getCount() {
return list.size();
}
#Override
public ModelPrivilegeDescriptionAccount getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = inflater.inflate(RESOURCE_ID, null);
HTextView accountNumber = convertView.findViewById(R.id.itemCorporationPrivilegeDescriptionAccountNumber);
HTextView changeLimitButton = convertView.findViewById(R.id.itemCorporationPrivilegeDescriptionChangeLimitButton);
LinearLayout layout = convertView.findViewById(R.id.itemCorporationAuthorityDescriptionLayout);
final ModelPrivilegeDescriptionAccount item = getItem(position);
accountNumber.setText(item.accountNumber);
changeLimitButton.setVisibility(item.isChangeable ? View.VISIBLE : View.GONE);
changeLimitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onLimitButtonClick(item);
}
});
accountNumber.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onDetailButtonClick(item);
}
});
return convertView;
}
public interface CorporationPrivilegeDescriptionListener {
void onLimitButtonClick(ModelPrivilegeDescriptionAccount item);
void onDetailButtonClick(ModelPrivilegeDescriptionAccount item);
}
}
i am having a small problem with memory when i tried to used nested RecyclerView and it crashed because it was not recycling views and as a result it run out of memory. So i have to go with another solution. I have created my own layout which accepts a Adapter like this:
public class CustomTileLayout extends LinearLayout {
private Adapter mAdapter;
private Observer mObserver = new Observer();
public CustomTileLayout(Context context) {
super(context);
}
public CustomTileLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public Adapter getAdapter() {
return mAdapter;
}
public void setAdapter(Adapter mAdapter) {
if (mAdapter != null)
mAdapter.unregisterDataSetObserver(mObserver);
this.mAdapter = mAdapter;
mAdapter.registerDataSetObserver(mObserver);
mObserver.onChanged();
}
private class Observer extends DataSetObserver {
#Override
public void onChanged() {
final List<View> oldViews = new ArrayList<View>(getChildCount());
for (int i = 0; i < getChildCount(); i++)
oldViews.add(getChildAt(i));
final Iterator<View> iter = oldViews.iterator();
removeAllViews();
for (int i = 0; i < mAdapter.getCount(); i++) {
View convertView = iter.hasNext() ? iter.next() : null;
View newView = mAdapter.getView(i, convertView, CustomTileLayout.this);
addView(newView);
}
super.onChanged();
}
#Override
public void onInvalidated() {
removeAllViews();
super.onInvalidated();
}
}
}
and while i use it like:
tileHolder = (GameCategoriesTileViewHolder) holder;
section = (Section) items.get(position);
tileHolder.customTileLayout.setAdapter(new GameTileAdapter(section.getGames(), context, R.layout.row_small_tile));
Everything works fine so far but there is a problem. The problem is that it looks like this:
while i want it each row to have 3 tiles like this:
If i specify the child layout to be like the result since it is the same item it only populates the 1st tile and the next 2 are blank.
My adapter:
public class GameTileAdapter implements ListAdapter {
private List<Game> games;
private Context context;
private int resLayout = R.layout.row_small_tile;
private boolean isFavoriteFragmentView = false;
private PopupMenu popupMenu;
public GameTileAdapter(List<Game> games, Context context, int resLayout) {
this.games = games;
this.context = context;
this.resLayout = resLayout;
}
#Override
public void registerDataSetObserver(DataSetObserver observer) {
}
#Override
public void unregisterDataSetObserver(DataSetObserver observer) {
}
#Override
public int getCount() {
return games.size();
}
#Override
public Object getItem(int position) {
return games.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
SingleItemViewHolder holder;
if (itemView == null){
LayoutInflater vi;
vi = LayoutInflater.from(context);
itemView = vi.inflate(resLayout, parent, false);
holder = new SingleItemViewHolder(itemView);
holder.game_name.setText(games.get(position).getName());
if (games.get(position).getImageUri().isEmpty()){
holder.game_imageuri.setImageResource(R.drawable.ic_image_placeholder);
}else {
Picasso.with(context).load(games.get(position).getImageUri()).into(holder.game_imageuri);
}
holder.itemLineColor.setBackgroundColor(GameManager.getmInstance(context).getGameColor(games.get(position)));
}else {
holder = (SingleItemViewHolder)itemView.getTag();
}
return itemView;
}
#Override
public boolean areAllItemsEnabled() {
return true;
}
#Override
public boolean isEnabled(int position) {
return true;
}
private static class SingleItemViewHolder{
CardView cv;
TextView game_name;
TextView game_is_new;
TextView game_jackpot;
ImageView game_imageuri;
View itemLineColor;
Button favorite_button;
Button menu_button;
SingleItemViewHolder(View itemView) {
cv = (CardView)itemView.findViewById(R.id.root_layout);
game_name = (TextView)itemView.findViewById(R.id.game_name_text);
game_is_new = (TextView)itemView.findViewById(R.id.game_new_ribbon);
game_jackpot = (TextView)itemView.findViewById(R.id.game_jackpot_ribbon);
game_imageuri = (ImageView)itemView.findViewById(R.id.game_imageuri);
itemLineColor = (View)itemView.findViewById(R.id.single_line_color);
favorite_button = (Button)itemView.findViewById(R.id.favButton);
menu_button = (Button)itemView.findViewById(R.id.menu_button_tile);
}
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return games.size();
}
#Override
public boolean isEmpty() {
return games.isEmpty();
}
}
Any ideas of how i can get the result?
You can use a layout for inner RecyclerView and add inflate a layout dynamically.
#Override
public void onBindViewHolder(RecentErrorsAdapter.ViewHolder holder, int position) {
try {
ArrayList<String> innerArrayList = new ArrayList<String>();
innerArrayList = mDataset.get(position).getInnerDataList();
for (int i = 0; i < innerArrayList.size(); i++) {
LayoutInflater inflater = null;
inflater = (LayoutInflater) context.getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View mLinearView = inflater.inflate(R.layout.your_layout, null);
/**
* getting id of row.xml
*/
TextView textName = (TextView) mLinearView
.findViewById(R.id.txt_name);
textName.setText(innerArrayList.get(i));
holder.lstProgramName.addView(mLinearView);
}
} catch (Exception e) {
e.printStackTrace();
}
}
I have a gridview with items that I can increase or diminish its values, what is happening is when I change the value of the item and scroll down the screen
and scroll back the change that I made is gone, and if I scroll down and up a couple times I can see the change that I made again, what am I missing here?
public class SearchItemViewAdapter extends RealmSearchAdapter<Itens, SearchItemViewAdapter.ViewHolder> implements RealmChangeListener {
public SparseBooleanArray mSparseBooleanArray;
public SearchItemViewAdapter(Activity context, Realm realm, String filterColumnName) {
super(context, realm, filterColumnName);
mSparseBooleanArray = new SparseBooleanArray();
}
#Override
public void onChange() {
notifyDataSetChanged();
}
public RealmList<Itens> getCheckedItems() {
RealmList<Itens> mTempArry = new RealmList<>();
for (int i = 0; i < realmResults.size(); i++) {
if (mSparseBooleanArray.get(i)) {
mTempArry.add(realmResults.get(i));
}
}
return mTempArry;
}
public class ViewHolder extends RealmSearchViewHolder {
public SearchItemView itemView;
public ViewHolder(FrameLayout container, TextView footerTextView) {
super(container, footerTextView);
}
public ViewHolder(SearchItemView itemView) {
super(itemView);
this.itemView = itemView;
}
}
#Override
public ViewHolder onCreateRealmViewHolder(ViewGroup viewGroup, int viewType) {
ViewHolder vh = new ViewHolder(new SearchItemView(viewGroup.getContext()));
return vh;
}
#Override
public void onBindRealmViewHolder(ViewHolder viewHolder, int position) {
final Itens item = realmResults.get(position);
viewHolder.itemView.bind(item);
viewHolder.itemView.check.setTag(position);
viewHolder.itemView.check.setChecked(mSparseBooleanArray.get(position));
viewHolder.itemView.check.setOnCheckedChangeListener(mCheckedChangeListener);
}
CompoundButton.OnCheckedChangeListener mCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mSparseBooleanArray.put((Integer) buttonView.getTag(), isChecked);
}
};
#Override
public ViewHolder onCreateFooterViewHolder(ViewGroup viewGroup) {
View v = inflater.inflate(R.layout.footer_view, viewGroup, false);
return new ViewHolder(
(FrameLayout) v,
(TextView) v.findViewById(R.id.footer_text_view));
}
#Override
public void onBindFooterViewHolder(ViewHolder holder, int position) {
super.onBindFooterViewHolder(holder, position);
holder.itemView.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
}
}
);
}
}
SearchItemView
public class SearchItemView extends RelativeLayout {
#Bind(R.id.codigo)
TextView codigo;
#Bind(R.id.nomeproduto)
TextView nome;
#Bind(R.id.preco)
TextView preco;
#Bind(R.id.valor)
TextView itemq;
#Bind(R.id.more)
ImageView more;
#Bind(R.id.less)
ImageView less;
#Bind(R.id.check)
CheckBox check;
final int nStart = 0;
final int nEnd = 10000000;
public SearchItemView(Context context) {
super(context);
init(context);
}
private void init(Context context) {
inflate(context, R.layout.add_itens_adapter, this);
ButterKnife.bind(this);
}
public void bind(Itens item) {
nome.setText(item.getNome());
codigo.setText(item.getCodigo());
preco.setText(item.getPreco());
more.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getString = String.valueOf(itemq.getText());
int curent = Integer.parseInt(getString);
if (v == more) {
if (curent < nEnd) {
curent++;
itemq.setText(String.valueOf(curent));
}
}
}
});
less.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getString = String.valueOf(itemq.getText());
int curent = Integer.parseInt(getString);
if (v == less) {
if (curent > nStart) {
curent--;
itemq.setText(String.valueOf(curent));
}
}
}
});
}
}
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);
}
}
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.