内容更改时如何重绘RecyclerView的父片段

时间:2019-05-17 08:53:02

标签: android android-fragments android-recyclerview

我建立了一个非常简单的在线商店。我使用BottomNavigationView浏览应用程序(有一个Activity包含navBar和从此栏中打开的多个Fragment)。在购物车的片段中,我有机会从购物车中删除商品。

然后发生以下问题:

  • 我删除了该项目,但只有RecyclerView得到更新,而不是整个片段。
  • 这是一个问题,因为片段的布局取决于RecyclerView的内容(如果recyclerView为空→隐藏整个布局等)

这是我的RecyclerView的onBindViewHolder:

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

基本上我的问题是:如何从CartAdapter更新片段的布局?还有其他方法可以实现所需的行为吗?

1 个答案:

答案 0 :(得分:0)

如果有人遇到这个问题:我终于通过界面解决了该问题:

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

购物车片段:

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

}