BaseAdapter inside RecyclerView shows only one item issue - android

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);
}
}

Related

How to fix my onClick cardView that is returning other figures

I have a recycler that is showing a list of items, there price and status. When I click on a card, I want it to show the price of the item that I have clicked on. However whenever, I click. The card returns the data of other cards and no the particular card that I have clicked.
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ItemHolder> {
private TextView viewName, viewPrice;
private CheckBox viewAvailability;
private Context context;
private List<Item> listItems;
#NonNull
#Override
public ItemAdapter.ItemHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
return new ItemAdapter.ItemHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ItemAdapter.ItemHolder holder, int position) {
Item item = listItems.get(position);
holder.setDetails(item);
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ItemHolder extends RecyclerView.ViewHolder {
public ItemHolder(final View itemView) {
super(itemView);
viewName = itemView.findViewById(R.id.viewName);
viewPrice = itemView.findViewById(R.id.viewPrice);
viewAvailability = itemView.findViewById(R.id.viewAvailability);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
public void setDetails(Item item) {
viewName.setText(item.getName());
viewPrice.setText(item.getPrice());
int as = item.getAvailabilityStatus();
if (as == 1) {
viewAvailability.setChecked(true);
} else {
}
}
}
public ItemAdapter(Context context, List<Item> objects) {
this.context = context;
this.listItems = objects;
}
}
Try this code,put itemView onclick listner inside setDetails
public void setDetails(Item item) {
viewName.setText(item.getName());
viewPrice.setText(item.getPrice());
int as = item.getAvailabilityStatus();
if (as == 1) {
viewAvailability.setChecked(true);
} else {
}
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// here you will able to access valid item
}
});
}
Try this code...
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ItemHolder> {
private Context context;
private List<Item> listItems;
#NonNull
#Override
public ItemAdapter.ItemHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
return new ItemHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ItemAdapter.ItemHolder holder, int position) {
Item item = listItems.get(position);
holder.viewName.setText(item.getName());
holder.viewPrice.setText(item.getPrice());
int as = item.getAvailabilityStatus();
if (as == 1) {
holder.viewAvailability.setChecked(true);
} else {
holder.viewAvailability.setChecked(false);
}
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ItemHolder extends RecyclerView.ViewHolder {
private TextView viewName, viewPrice;
private CheckBox viewAvailability;
public ItemHolder(final View itemView) {
super(itemView);
viewName = itemView.findViewById(R.id.viewName);
viewPrice = itemView.findViewById(R.id.viewPrice);
viewAvailability = itemView.findViewById(R.id.viewAvailability);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
}
public ItemAdapter(Context context, List<Item> objects) {
this.context = context;
this.listItems = objects;
}
}
Insted of itemView.setOnClickListener use set clickListener on your cardView and use getAdapterPosition() to track which item you click
cardView= itemView.findViewById(R.id.cardView);
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int price = getThePrice(getAdapterPosition());
// use price here
}
});
you have to create getThePrice() method here which will return you the price of item you click.

list is not expanding / collapsing for second time

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;
}
}

set onClickListener on Imageview(Listview) inside activity

Is there a way to set onClickListener on Imageview(Listview) inside activity ?
I'v created this , and it works just fine in my adapter, But it's not working in my activity :
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
playPause=(ImageView)view.findViewById(R.id.playPause);
Product m = productList.get(position);
playPause.setImageResource(m.getPlayPauseId());
playPause.setTag(position);
playPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = (Integer) v.getTag();
Product m =productList.get(pos);
if (paused) {
m.setPlayPauseId(R.drawable.ic_pause);
paused=false;
}else {
m.setPlayPauseId(R.drawable.ic_play);
paused = true;
}
adapter.notifyDataSetChanged();
}
});
}
And this is my Product class :
public class Product implements Serializable {
private int PlayPauseId;
#SerializedName("pid")
public int pid;
#SerializedName("name")
public String name;
#SerializedName("qty")
public int qty;
#SerializedName("price")
public String description;
#SerializedName("image_url")
public String image_url;
#SerializedName("date")
public String date;
public int getPlayPauseId() {
return PlayPauseId;
}
public void setPlayPauseId(int playPauseId) {
PlayPauseId = playPauseId;
}
}
Adapter Class (Fundapter library) :
public class FunDapter<T> extends BaseAdapter implements Filterable {
protected List<T> mDataItems;
protected List<T> mOrigDataItems;
protected LongExtractor<T> idExtractor;
protected final Context mContext;
private final int mLayoutResource;
private final BindDictionary<T> mBindDictionary;
private int oddColorRes;
private int evenColorRes;
private FunDapterFilter<T> funDapterFilter;
private Filter mFilter;
public FunDapter(Context context, List<T> dataItems, int layoutResource,
BindDictionary<T> dictionary) {
this(context, dataItems, layoutResource, null, dictionary);
}
public FunDapter(Context context, List<T> dataItems, int layoutResource,
LongExtractor<T> idExtractor, BindDictionary<T> dictionary) {
this.mContext = context;
this.mDataItems = dataItems;
this.mOrigDataItems = dataItems;
this.mLayoutResource = layoutResource;
this.idExtractor = idExtractor;
this.mBindDictionary = dictionary;
}
public void updateData(List<T> dataItems) {
this.mDataItems = dataItems;
this.mOrigDataItems = dataItems;
notifyDataSetChanged();
}
#Override
public int getCount() {
if (mDataItems == null || mBindDictionary == null) return 0;
return mDataItems.size();
}
#Override
public T getItem(int position) {
return mDataItems.get(position);
}
#Override
public boolean hasStableIds() {
if(idExtractor == null) return super.hasStableIds();
else return true;
}
#Override
public long getItemId(int position) {
if(idExtractor == null) return position;
else return idExtractor.getLongValue(getItem(position), position);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
final GenericViewHolder holder;
if (null == v) {
LayoutInflater vi =
(LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(mLayoutResource, null);
holder = new GenericViewHolder();
holder.root = v;
FunDapterUtils.initViews(v, holder, mBindDictionary);
v.setTag(holder);
} else {
holder = (GenericViewHolder) v.getTag();
}
final T item = getItem(position);
showData(item, holder, position);
return v;
}
you can do it with two ways:
Make an interface something like this
public interface ImageClick {
public imageButtonOnClick(View view, int position)
}
implement it in your activity, and in your adapter getView, set imageOnClickListener, and call this interface method inside that onClick, pass your position and view in it, so you can use position etc in your activity callback.
Second is to just make a method in your activity like in interface
public imageButtonOnClick(View view, int position)
in your adapter onClick method on imageView, call it something like
((YourActivity)context).imageButtonOnClick(params1, param2);
Custom your ArrayAdapter and set action in method getView
See this page
ListView with Add and Delete Buttons in each Row in android
For getting click the image in the list view in the activity itself you have to callback
Create an interface
public interface OnButtonClickListener {
public void onButtonClick(int position,View view);
}
in your actvity class implement OnButtonClickListener
you get a interface methood
#Override
public void onButtonClick(final int position, View view) {
int id = view.getId();
switch (id) {
case R.id.YOURIMAGEVIEWID:
//implent your process...
}
}
Create constructor in adapter calss
Context context;
OnButtonClickListener callback
public AdapterClass(Context context OnButtonClickListener buttonClickListener) {
this.context = context;
callback = buttonClickListener;
}
image click in adapter class
holder.imageView..setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callback.onButtonClick(position, v);
}
});
in your actvity class
AdapterClass Adapter = new AdapterClass(youractivity.this, youractivity.this);
Add this class for callback
public class ListCustomClickEvents implements OnClickListener,View.OnTouchListener {
private int position;
private OnCustomClickListener callback;
// Pass in the callback (this'll be the activity) and the row position
public ListCustomClickEvents(OnCustomClickListener callback, int pos) {
position = pos;
this.callback = callback;
}
#Override
public void onClick(View v) {
callback.OnCustomClick(v, position);
}
}

Replace Recyclerview with LinearLayout

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();
}
}

RealmSearchAdapter not recylcing the view

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));
}
}
}
});
}
}

Categories

Resources