thanks for helping. I was trying to implement an add to favorite function in my recycler view, everything is working fine except for one thing. I am unable to commit the changed image button in my recycler view, every time I press the button, the post is added to the favorites and the image button turns yellow, but as soon as I move to some other fragment, the yellow button goes back to its initial stage. Can anyone of you help me on how can I make my button commit to the changes in recycler view. Below is my relevant code.
Initialization of buttons in holder class:
class UsersViewHolder1 extends RecyclerView.ViewHolder {
View mView;
private ImageButton mFavouritesBlack, mFavouritesYellow;
private GestureDetector mGestureDetector;
private Heart mHeart;
public UsersViewHolder1(View itemView) {
super(itemView);
mView = itemView;
mFavouritesBlack = mView.findViewById(R.id.ad_start_fav);
mFavouritesYellow = mView.findViewById(R.id.ad_start_fav1);
}
}
OnBindViewHOlder class(I omitted the irrelevant code):
protected void onBindViewHolder(@NonNull final UsersViewHolder1 Holder, final int position, @NonNull
Ad ad) {
Holder.setTitle(ad.getTitle());
Holder.setPrice(ad.getPrice());
Holder.setCategory(ad.getCategory());
Holder.setImage(ad.getImage(), getContext());
Holder.setTime(ad.getTime());
String user_id = getRef(position).getKey();
final String kk = user_id.toString();
Holder.mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent mew = new Intent(getActivity(), ExpandActivity.class);
mew.putExtra("user_id", kk);
startActivity(mew);
}
});
Holder.mFavouritesBlack.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
mFav.child(puid).child(kk).child("fav_status").setValue("Added as fav").addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Toast.makeText(getContext(),"Added to Fav",Toast.LENGTH_SHORT).show();
if (Holder.mFavouritesBlack.isShown())
Holder.mFavouritesBlack.setVisibility(View.GONE);
Holder.mFavouritesYellow.setVisibility(View.VISIBLE);
}
});
return true;
}
});
Holder.mFavouritesYellow.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
mFav.child(puid).child(kk).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Toast.makeText(getContext(),"Removed from Fav",Toast.LENGTH_SHORT).show();
if (Holder.mFavouritesYellow.isShown())
Holder.mFavouritesBlack.setVisibility(View.VISIBLE);
Holder.mFavouritesYellow.setVisibility(View.GONE);
}
});
return true;
}
});
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…