I've built a very simple online shop. I navigate through the app by using a BottomNavigationView (There is one Activity containing the navBar and multiple Fragments which are opened from this bar). In the Fragment for the shoppingcart I give the opportunity to remove items from the cart.
Then following problems occurs:
So here is my onBindViewHolder for the RecyclerView:
CartAdapter:
@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final int pos = position;
Item item = CartViewModel.getInstance().mShoppingCartItems.get(position);
vh.nameTextView.setText(item.getmTitle());
vh.quantityTextView.setText(String.valueOf("Anzahl: " + item.getmQuantity()));
vh.priceTextView.setText("€ " + item.getmPrice());
vh.nameTextView.setAllCaps(true);
vh.deleteButton.setBackground(null);
Picasso.with(mContext).load(item.getmPictureLink()).into(vh.pictureImageView);
holder.deleteButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Item theRemovedItem = CartViewModel.getInstance().mShoppingCartItems.get(pos);
CartViewModel.getInstance().mShoppingCartItems.remove(pos);
notifyItemRemoved(pos);
//force the parent Fragment to update it's layout
}
});
}
Basically my question is: How can i update the layout of the fragment from my CartAdapter? Is there any other way to accomplish the desired behavior?
If somebody else comes across this: i finally resolved the issue with an interface :
public interface CartCallback {
void onMethodCallback();
}
CartAdapter:
public class CartAdapter extends RecyclerView.Adapter < CartAdapter.ViewHolder > {
private CartCallback mAdapterCallback;
CartAdapter(CartCallback callback) {
this.mAdapterCallback = callback;
}
public void onBindViewHolder(ViewHolder holder, @SuppressLint("RecyclerView") final int position) {
// ....
holder.deleteButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CartViewModel.getInstance().mShoppingCartItems.remove(position);
notifyItemRemoved(position);
mAdapterCallback.onMethodCallback();
}
});
}
}
CartFragment:
public class CartFragment extends Fragment implements CartCallback {
@Override
public void onCreate(Bundle savedInstanceState) {
this.adapter = new CartAdapter(this);
}
@Override
public void onMethodCallback() {
Fragment frg = getActivity().getSupportFragmentManager().findFragmentByTag("CartFragment");
final FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.detach(frg);
ft.attach(frg);
ft.commit();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.