How to check RecycleView multiple item View Id in OnClick - android

I want to do different job for different RecycleView item. I created custom OnClickListener for RecycleView and using this from my activity. But problem is when I want to get RecycleView Item Id form OnClick it's return -1. I can't able to check view Id.
RecycleView Adapter:
public class AddFoodAdapter extends RecyclerView.Adapter<AddFoodAdapter.AddFoodApapterVH>{
private ArrayList<FoodReviewItem> foodList = new ArrayList<>();
OnItemClickListener onItemClickListener;
public AddFoodAdapter(){
}
#Override
public AddFoodApapterVH onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recycleview_add_food_item, parent, false);
return new AddFoodApapterVH(itemView);
}
#Override
public void onBindViewHolder(AddFoodApapterVH holder, int position) {
holder.tvFoodTitle.setText(foodList.get(position).getFoodName());
holder.tvFoodPrice.setText(foodList.get(position).getFoodPrice());
}
public void add(int position,FoodReviewItem foodItem){
foodList.add(position,foodItem);
notifyItemInserted(position);
}
public void delete(int position){
foodList.remove(position);
notifyItemRemoved(position);
}
#Override
public int getItemCount() {
return foodList.size();
}
public class AddFoodApapterVH extends RecyclerView.ViewHolder implements View.OnClickListener{
public ImageView ivEditFoodItem;
public TextView tvFoodTitle;
public RatingBar rbFoodRating;
public ImageView ivDeleteFoodItem;
public TextView tvFoodPrice;
public AddFoodApapterVH(View itemView) {
super(itemView);
ivEditFoodItem = (ImageView) itemView.findViewById(R.id.ivEditFoodItem);
tvFoodTitle = (TextView) itemView.findViewById(R.id.tvAddFoodItemTitle);
rbFoodRating = (RatingBar) itemView.findViewById(R.id.rbAddFoodItemRating);
ivDeleteFoodItem = (ImageView) itemView.findViewById(R.id.ivDeleteFoodItem);
tvFoodPrice = (TextView) itemView.findViewById(R.id.tvAddFoodItemPrice);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(onItemClickListener!=null){
onItemClickListener.onItemClick(v, getAdapterPosition());
}
}
}
public interface OnItemClickListener {
public void onItemClick(View view , int position);
}
public void SetOnItemClickListener(final OnItemClickListener onItemClickListener){
this.onItemClickListener = onItemClickListener;
}
}
Form Activity:
private void setUpFoodItemApapter() {
foodItemRecyclerView = (RecyclerView) findViewById(R.id.rvFoodItems);
addFoodAdapter = new AddFoodAdapter();
final LinearLayoutManager layoutManager = new org.solovyev.android.views.llm.LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
foodItemRecyclerView.setLayoutManager(layoutManager);
foodItemRecyclerView.addItemDecoration(new DividerItemDecoration(this, null));
foodItemRecyclerView.setAdapter(addFoodAdapter);
addFoodAdapter.SetOnItemClickListener(new AddFoodAdapter.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Log.i("getid",""+view.getId()); //return -1
Log.i("getid",""+R.id.ivDeleteFoodItem); //return id
// not working
if(view.getId() == R.id.ivDeleteFoodItem){
addFoodAdapter.delete(position);
}
}
});
}

addFoodAdapter.SetOnItemClickListener(new AddFoodAdapter.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
ImageView iv = (ImageView)view;// get imageView
int id = iv.getId();
if(id == R.id.ivDeleteFoodItem){
addFoodAdapter.delete(position);
}
}
});

Related

Should I create adapter for every recyclerview?

I am using diffutil for my recycler adapters and I need many recyclerview for categorization. Should I create adapter for every recyclerview? Same view, same type data, same functions, different data btw
If you check your recycler view's onBindViewHolder method it has your holder parameter which provides you with the instance of different ViewHolders you have and accordingly set the layout for the recycler view.
For example, in my case I had to use a single recyclerView adapter to create an instance Income as well as expense in a list.
This is how my onBindViewHolder looks:
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
DialogDetails d=new DialogDetails();
if (holder instanceof IncomeListHolder){
((IncomeListHolder)holder).categoryText.setText(expensesList.get(position).getCategory());
((IncomeListHolder)holder).incomeText.setText("+"+expensesList.get(position).getAmount());
((IncomeListHolder)holder).incomeText.setTextColor(context.getResources().getColor(R.color.income_color));
}
if (holder instanceof ExpensesListHolder){
((ExpensesListHolder) holder).category.setText(list.get(position-expensesList.size()).getCategory());
((ExpensesListHolder) holder).expenseText.setText("-"+list.get(position- expensesList.size()).getExpense());
((ExpensesListHolder) holder).expenseText.setTextColor(context.getResources().getColor(R.color.expense_color));
}
//.setText(String.valueOf(balanceList.get(position).getIncome()));
}
You also have to create separate viewHolders for all the list data you wish to display,like:
public class IncomeListHolder extends RecyclerView.ViewHolder {
TextView categoryText;
TextView incomeText;
public IncomeListHolder(#NonNull View itemView) {
super(itemView);
categoryText=itemView.findViewById(R.id.main_category_text_view);
incomeText=itemView.findViewById(R.id.expenses_text_view);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position=getAdapterPosition();
if (listener!=null && position!=RecyclerView.NO_POSITION){
listener.getIncomeData(expensesList.get(position),view);
details.setUpdate(true);
}
}
});
}
}
public class ExpensesListHolder extends RecyclerView.ViewHolder{
TextView category;
TextView expenseText;
public ExpensesListHolder(#NonNull View itemView) {
super(itemView);
category=itemView.findViewById(R.id.main_category_text_view_2);
expenseText=itemView.findViewById(R.id.expenses_text_view_2);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position=getAdapterPosition();
if (listener!=null && position!=RecyclerView.NO_POSITION){
listener.getExpenseData(list.get(position-expensesList.size()),view);
details.setUpdate(true);
}
}
});
}
}
My whole recycler view adapter:
public class IncomeListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
final int VIEW_TYPE_INCOME=0;
final int VIEW_TYPE_EXPENSE=1;
View view;
List<DataBaseEntity> expensesList=new ArrayList<>();
List<ExpenseDataEntity> list=new ArrayList<>();
Context context;
OnItemClickListener listener;
DialogDetails details=new DialogDetails();
public IncomeListAdapter(Context context) {
this.context = context;
}
//
// View v=LayoutInflater.from(context).inflate(R.layout.fragment_expense_home,null);
//// t=v.findViewById(R.id.income_text_view);
// }
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType==VIEW_TYPE_INCOME) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.expenses_list, parent, false);
return new IncomeListHolder(view);
}
if (viewType==VIEW_TYPE_EXPENSE){
view=LayoutInflater.from(parent.getContext()).inflate(R.layout.expense_layout_list,parent,false);
return new ExpensesListHolder(view);
}
return null;
}
public interface OnItemClickListener{
void getIncomeData(DataBaseEntity dataBaseEntity,View view);
void getExpenseData(ExpenseDataEntity expenseDataEntity,View view);
}
public void setOnItemClickListener(OnItemClickListener listener){
this.listener=listener;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
DialogDetails d=new DialogDetails();
if (holder instanceof IncomeListHolder){
((IncomeListHolder)holder).categoryText.setText(expensesList.get(position).getCategory());
((IncomeListHolder)holder).incomeText.setText("+"+expensesList.get(position).getAmount());
((IncomeListHolder)holder).incomeText.setTextColor(context.getResources().getColor(R.color.income_color));
}
if (holder instanceof ExpensesListHolder){
((ExpensesListHolder) holder).category.setText(list.get(position-expensesList.size()).getCategory());
((ExpensesListHolder) holder).expenseText.setText("-"+list.get(position- expensesList.size()).getExpense());
((ExpensesListHolder) holder).expenseText.setTextColor(context.getResources().getColor(R.color.expense_color));
}
//.setText(String.valueOf(balanceList.get(position).getIncome()));
}
public DataBaseEntity getDataAt(int position){
return expensesList.get(position);
}
public ExpenseDataEntity getExpenseAt(int position){
return list.get(position- expensesList.size());
}
#Override
public int getItemCount() {
return expensesList.size()+list.size();
}
#Override
public int getItemViewType(int position) {
if (position< expensesList.size()){
return VIEW_TYPE_INCOME;
}
if (position-expensesList.size()< list.size()){
return VIEW_TYPE_EXPENSE;
}
return -1;
}
public void setExpensesList(List<DataBaseEntity> expensesList){
this.expensesList=expensesList;
notifyDataSetChanged();
}
public void setList(List<ExpenseDataEntity> list){
this.list=list;
notifyDataSetChanged();
}
// public void setBalanceList(List<BalanceSheetEntity> balanceList){
// this.balanceList=balanceList;
// notifyDataSetChanged();
// }
public class IncomeListHolder extends RecyclerView.ViewHolder {
TextView categoryText;
TextView incomeText;
public IncomeListHolder(#NonNull View itemView) {
super(itemView);
categoryText=itemView.findViewById(R.id.main_category_text_view);
incomeText=itemView.findViewById(R.id.expenses_text_view);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position=getAdapterPosition();
if (listener!=null && position!=RecyclerView.NO_POSITION){
listener.getIncomeData(expensesList.get(position),view);
details.setUpdate(true);
}
}
});
}
}
public class ExpensesListHolder extends RecyclerView.ViewHolder{
TextView category;
TextView expenseText;
public ExpensesListHolder(#NonNull View itemView) {
super(itemView);
category=itemView.findViewById(R.id.main_category_text_view_2);
expenseText=itemView.findViewById(R.id.expenses_text_view_2);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position=getAdapterPosition();
if (listener!=null && position!=RecyclerView.NO_POSITION){
listener.getExpenseData(list.get(position-expensesList.size()),view);
details.setUpdate(true);
}
}
});
}
}
}

Android RecyclreView OnCLick Listener

Error on android recyclerView Adapter. App will stop working while click on RecyclerView items. I want to go other activity when click any items, when i'm using Toast it working fine but if i add Intent then it stop working.
Here is my Interface :
public interface OnItemClickListener {
void onClick(View view, int position);
}
here is my recycler Adapter calss :
public class RecAdapter extends RecyclerView.Adapter<RecAdapter.MyViewHolder> {
private List<Items> items;
private Context context;
public RecAdapter(List<Items> items, Context context )
{
this.items = items;
this.context = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.countryname.setText(items.get(position).getCountryname());
holder.rank.setText(items.get(position).getRank());
Picasso.with(context)
.load(items.get(position).getFlag())
.into(holder.flag);
holder.setClickListener(new OnItemClickListener() {
#Override
public void onClick(View view, int position) {
Intent intent = new Intent(context , Main2Activity.class);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return items.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView countryname, rank;
ImageView flag;
private OnItemClickListener clickListener;
public MyViewHolder(View itemView) {
super(itemView);
countryname = (TextView) itemView.findViewById(R.id.capital);
rank = (TextView) itemView.findViewById(R.id.rank);
flag = (ImageView) itemView.findViewById(R.id.flag);
itemView.setTag(itemView);
itemView.setOnClickListener(this);
}
public void setClickListener(OnItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
#Override
public void onClick(View view) {
if (clickListener != null) clickListener.onClick(view, getAdapterPosition());
}
}
}
Add click listener like this:-
View itemView;
Context context;
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view, parent, false);
this.context=parent.getContext();
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context , Main2Activity.class);
context.startActivity(intent);
}
});
}
copying an answer of mine from a different question:
as you already know this method is no longer available in the RecyclerView class.
My approach towards implementing onClick events in a RecyclerView is something like this:
class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
interface OnClickListener {
void onClick(Item item);
}
private final List<Item> dataset;
private final OnClickListener l;
public MyAdapter(List<Item> data, OnClickListener listener) {
this.dataset = data;
this.l = listener;
}
#Override MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = //inflate layout
MyClick click = new MyClick() {
onClick(int position) {
if (l != null) {
l.onClick(dataset.get(position));
}
}
};
return new MyViewHolder(click, v);
}
static class MyViewHolder {
final MyClick l;
public MyViewHolder(MyClick listener, View view) {
super(view);
l = listener;
// inflate views
view.setOnClickListener(new OnClickListener() {
if (l != null) {
l.onClick(getAdapterPosition());
}
});
}
interface MyClick {
void onClick(int position);
}
}
}
class MyActivity extends AppCompatActivity {
#Override void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set layout
MyAdapter adapter = new MyAdapter(getData(), new OnClickListener() {
#Override onClick(Item item) {
// do stuff with item
}
});
}
}
You can not click an holder directly..... give a id to the view then re write the code as below:
holder.(someitem).setClickListener(new OnItemClickListener() {//you need a view to execute the onclicklistener
#Override
public void onClick(View view, int position) {
Intent intent = new Intent(context , Main2Activity.class);
context.startActivity(intent);
}
});
Here is code which i create click listener for Recycler Item Click
Using this you will get two types of click
Simple Item click.
Item Long click.
Here is RecyclerItemClickListener.java File
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
public interface OnItemClickListener
{
void onItemClick(View view, int position);
void onItemLongClick(View view, int position);
}
private OnItemClickListener mListener;
private GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener)
{
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener()
{
#Override
public boolean onSingleTapUp(MotionEvent e)
{
return true;
}
#Override
public void onLongPress(MotionEvent e)
{
View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());
if(childView != null && mListener != null)
{
mListener.onItemLongClick(childView, recyclerView.getChildPosition(childView));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e)
{
View childView = view.findChildViewUnder(e.getX(), e.getY());
if(childView != null && mListener != null && mGestureDetector.onTouchEvent(e))
{
mListener.onItemClick(childView, view.getChildPosition(childView));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent){}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
How to use in Activity and Fragment
rvcyclerView.addOnItemTouchListener(new RecyclerItemClickListener(context, rvcyclerView,
new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
//do you what you want tot do simple click
}
#Override
public void onItemLongClick(View view, int position) {
//do you what you want tot do on long click
}
}));
public class RecAdapter extends RecyclerView.Adapter<RecAdapter.MyViewHolder> implements View.OnClickListener {
private List<Items> items;
private Context context;
private OnItemClickListener clickListener;
public RecAdapter(List<Items> items, Context context )
{
this.items = items;
this.context = context;
}
public void setClickListener(OnItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.countryname.setText(items.get(position).getCountryname());
holder.rank.setText(items.get(position).getRank());
Picasso.with(context)
.load(items.get(position).getFlag())
.into(holder.flag);
holder.flag.setOnClickListener(this);
}
#Override
public int getItemCount() {
return items.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView countryname, rank;
ImageView flag;
public MyViewHolder(View itemView) {
super(itemView);
countryname = (TextView) itemView.findViewById(R.id.capital);
rank = (TextView) itemView.findViewById(R.id.rank);
flag = (ImageView) itemView.findViewById(R.id.flag);
}
#Override
public void onClick(View view) {
if (clickListener != null) clickListener.onClick(view, getAdapterPosition());
}
}
}
On Your Activity / Fragment Implement OnItemClickListener
public class MainActivity extends AppCompatActivity implements OnItemClickListener{
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayoutManager layout = new
LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(layout );
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
RecAdapter adapter = new RecAdapter(items ,getContext());
adapter.setClickListener(this);
mRecyclerView.setAdapter(adapter );
}
#Override
public void onClick(View view, int position) {
switch(view.getId()) {
}
}
}

How to get image from recyclerview position clicked data and set it into another imageview?

I have an app which contains recyclerview with imageview and text.When I click on item based on position that is imageview i want image of that image view and set it to another Imageview.To do this I have made interface and implements its method in Activity but need to know that how do i do that
Adapter code:
public interface OnItemClicked {
void onItemClicked(int position);
}
public AvatarListAdapter(Context context, int[] arrayList) {
this.mContext = context;
this.dataModel = arrayList;
}
#Override
public AvatarListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.avatar_items, parent, false);
return new AvatarListAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(AvatarListAdapter.ViewHolder holder, final int position) {
holder.mAvatarImage.setImageResource(dataModel[position]);
holder.mAvatarImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClick.onItemClicked(position);
}
});
}
public void setOnClick(OnItemClicked onClick) {
this.onClick = onClick;
}
#Override
public int getItemCount() {
return dataModel.length;
}
public class ViewHolder extends RecyclerView.ViewHolder {
private CircleImageView mAvatarImage;
public ViewHolder(View itemView) {
super(itemView);
mAvatarImage = itemView.findViewById(R.id.img_avatar);
}
}
}
Activity code:
private void initializeActions() {
int numberOfColumns = 3;
mAvatarImages.setLayoutManager(new GridLayoutManager(AvatarProfileImage.this, numberOfColumns));
mAdapter = new AvatarListAdapter(AvatarProfileImage.this, avatar);
mAvatarImages.setAdapter(mAdapter);
mAdapter.setOnClick(this);
}
#Override
public void onItemClicked(int position) {
String pos = "You clicked at position " + position;
Toast.makeText(getApplicationContext(), "You clicked position" + pos, Toast.LENGTH_LONG).show();
mAvatarImages.setBackgroundResource(avatar[position]);
}
You can get data by position on OnClick().As you are using local drawable for image resource, One way to do is Modify your viewHolder as follows.This is just a one way you can also use ViewTag.
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private Circle mAvatarImage;
public ViewHolder(View itemView) {
super(itemView);
mAvatarImage = itemView.findViewById(R.id.img_avatar);
mAvatarImage.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int postion =getAdapterPosition();
int image =arrayList[postion];
// Use this image to forward
}
}
Remove OnClick from onBindViewHolder.
Implement RecycleView onClick() method and get specified data while onclick position.have look
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private Circle mAvatarImage;
public ViewHolder(View itemView) {
super(itemView);
mAvatarImage = itemView.findViewById(R.id.img_avatar);
mAvatarImage.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int position=arrayList[getAdapterPosition()];
String imagepath = arraylist.get(position).getImagePath
//you can use imagepath anywhere you want either be put in bundle or intent call
}
}
Adapter code should look like this
private final OnItemClickListener listenerOnItemClick;
public interface OnItemClickListener {
void onItemClick(int position); }
public AvatarListAdapter(Context context, int[] arrayList, OnItemClickListener listenerOnItemClick) {
this.mContext = context;
this.dataModel = arrayList;
this.listenerOnItemClick=listenerOnItemClick;
}
#Override
public AvatarListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.avatar_items, parent, false);
return new AvatarListAdapter.ViewHolder(view); }
#Override
public void onBindViewHolder(AvatarListAdapter.ViewHolder holder, final int position) {
holder.mAvatarImage.setImageResource(dataModel[position]);
holder.mAvatarImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClick.onItemClicked(position);
}
}); }
public void setOnClick(OnItemClicked onClick) {
this.onClick = onClick; }
#Override
public int getItemCount() {
return dataModel.length; }
public class ViewHolder extends RecyclerView.ViewHolder {
private CircleImageView mAvatarImage;
public ViewHolder(View itemView) {
super(itemView);
mAvatarImage = itemView.findViewById(R.id.img_avatar);
} }
Activity Code
AvatarListAdapter.OnItemClickListener onItemClickListener = new AvatarListAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
//change your Image here
String pos = "You clicked at position " + position;
Toast.makeText(getApplicationContext(), "You clicked position" + pos, Toast.LENGTH_LONG).show();
mAvatarImages.setBackgroundResource(avatar[position]);
}
};
private void initializeActions() {
int numberOfColumns = 3;
mAvatarImages.setLayoutManager(new GridLayoutManager(AvatarProfileImage.this, numberOfColumns));
mAdapter = new AvatarListAdapter(AvatarProfileImage.this, avatar,onItemClickListener );
mAvatarImages.setAdapter(mAdapter);
mAdapter.setOnClick(this);
}

Recyclerview old item view doesn't remove when click another item?

I have a recyclerview . I click on a item. It is highlighted ( sets background - color) . And then, I click another item , It doesn't remove old highlighted view. My class is very leak . Also could you give me an advice to make more effective ?
public class DrawerMenuShelfListAdapter extends RecyclerView.Adapter<DrawerMenuShelfListAdapter.ViewHolder> implements View.OnClickListener {
private int selectedRow = 0;
public Fragment fragment;
public ViewHolder holder;
public RecyclerView recyclerView;
private ArrayList<ShelfModel> shelfList;
public DrawerMenuShelfListAdapter(Fragment fragment, ArrayList<ShelfModel> shelfList, RecyclerView recyclerView) {
this.shelfList = shelfList;
this.fragment = fragment;
this.recyclerView = recyclerView;
}
public void setItemSelected(int position){
recyclerView.getChildAt(selectedRow).setBackgroundColor(fragment.getActivity().getResources().getColor(android.R.color.transparent));
notifyItemChanged(selectedRow);
selectedRow = position;
recyclerView.getChildAt(selectedRow).setBackgroundColor(fragment.getActivity().getResources().getColor(android.R.color.black));
notifyItemChanged(selectedRow);
}
public void updateList(ArrayList<ShelfModel> list){
shelfList.clear();
shelfList.addAll(list);
notifyDataSetChanged();
notifyItemChanged(selectedRow);
}
#Override
public DrawerMenuShelfListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v= LayoutInflater.from(parent.getContext())
.inflate(R.layout.navigation_drawer_list_row, parent, false);
holder = new ViewHolder(v);
holder.text = (TextView) v.findViewById(R.id.definitionText);
holder.total = (TextView) v.findViewById(R.id.countText);
holder.editButton = (ImageButton)v.findViewById(R.id.editButton);
holder.text.setTypeface(App.MUSEO_100);
holder.total.setTypeface(App.MUSEO_300);
return holder;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final ShelfModel shelfModel = shelfList.get(position);
holder.text.setText(shelfModel.getName());
holder.total.setText(String.valueOf(shelfModel.getTotal()));
holder.shelfId = shelfModel.getShelfId();
holder.itemView.setOnClickListener(this);
}
#Override
public int getItemCount() {
return shelfList.size();
}
#Override
public void onClick(View v) {
int position = recyclerView.getChildLayoutPosition(v);
((DrawerMenuShelfListListener)fragment).onShelfItemClick(shelfList.get(position));
setItemSelected(position);
}
public interface DrawerMenuShelfListListener extends BaseRecyclerViewListener {
void onShelfItemClick(ShelfModel shelfModel);
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView text;
public TextView total;
public ImageView editButton;
public int shelfId;
public ViewHolder(View view) {
super(view);
}
}
}
Ok. I found the solution.If I don't call notifyItemChanged , it works

Removing item from RecyclerView

I am having trouble removing items from RecyclerView. When I click on delete, the item is removed from RecyclerView, but comes back when I open the app again. I'm hoping it is just a minor issue that someone here can point out or direct me to what area to troubleshoot. The removeItem(String item) in bold is what I think is the issue. You can't see it in this post, but it is "not used".
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
private List<Grocery> mListData;
private SQLGroceryHelper helper;
RecyclerViewAdapter adapter;
//Adapter's Constructor//
public RecyclerViewAdapter(List<Grocery> mDataList) {
this.mListData = mDataList;
}
//Provide a reference to the views for each contact item//
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView rowItem;
ImageButton purchasedButton;
ImageButton deleteButton;
LinearLayout linearLayout;
public MyViewHolder(View itemView) {
super(itemView);
linearLayout = (LinearLayout) itemView.findViewById(R.id.recycler_row);
rowItem = (TextView) itemView.findViewById(R.id.item_field1);
purchasedButton = (ImageButton) itemView.findViewById(R.id.item_purchased);
deleteButton = (ImageButton) itemView.findViewById(R.id.delete_item);
}
}
//Inflate the view based on the viewtype provided//
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//Create a new view by inflating the row item xml//
View row = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_row, parent, false);
//Set the view to the ViewHolder//
MyViewHolder holder = new MyViewHolder(row);
return holder;
}
//Display data at the specified position//
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.rowItem.setText(mListData.get(position).getTextItem());
holder.purchasedButton.setOnClickListener(new View.OnClickListener() {
//Ignore this click for now//
#Override
public void onClick(View v) {
removeItem(position);
}
});
holder.deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removeItem(position);
}
});
}
public void **removeItem**(String item) {
int position = mListData.indexOf(item);
if (position != -1) {
mListData.remove(item);
notifyItemRemoved(position);
}
}
public void removeItem(int position) {
mListData.remove(position);
notifyItemRemoved(position);
}
#Override
public int getItemCount() {
if (mListData == null) {
return 0;
}
return mListData.size();
}
}
You are removing the data from local object, mListData I guess the original data object remains intact. Remove the data item from the original data object as well
Declare a interface
public interface AdapterCommunication{
void removeStringItem(int position);
}
then in your adapter
private AdapterCommunication mListener;
public void setOnClickListener(AdapterCommunication listener){
mListener = listener;
}
Then from your activity where you initialize the adapter
RecyclerViewAdapter adapter = new RecyclerViewAdapter(list);
adapter.setOnClickListener(new AdapterCommunication{
public void removeStringItem(int position){
list.remove(position);
adapter.notifyDataSetChanged();
}
});
In your adaper,
holder.deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListener.remove(position);
}
});

Categories

Resources