Android : Change cart menu badge counter from Recycler Adapter

前提是你 提交于 2019-12-03 21:39:18

Since you already have a Context in your Adapter. You can cast that to Activity. This way you have access to the menu.

//when item is added or removed
((Activity)this.context).invalidateOptionsMenu()

In your Fragment.onCreateOptionsMenu you can go ahead and set the item count

In your fragment click event:

((MainActivity) getActivity()).createCartBadge("value");

Your activity contains this method:

public void createCartBadge(int i) {
        MenuItem cartItem = mToolbarMenu.findItem(R.id.cart);
        LayerDrawable localLayerDrawable = (LayerDrawable) cartItem.getIcon();
        Drawable cartBadgeDrawable = localLayerDrawable
                .findDrawableByLayerId(R.id.ic_badge);
        BadgeDrawable badgeDrawable;
        if ((cartBadgeDrawable != null)
                && ((cartBadgeDrawable instanceof BadgeDrawable))
                && (i < 10)) {
            badgeDrawable = (BadgeDrawable) cartBadgeDrawable;
        } else {
            badgeDrawable = new BadgeDrawable(MainActivity.this);
        }
        badgeDrawable.setCount(i);
        localLayerDrawable.mutate();
        localLayerDrawable.setDrawableByLayerId(R.id.ic_badge, badgeDrawable);
        cartItem.setIcon(localLayerDrawable);
    }

You can use Interface to communicate between the Fragment and the Adapter.

for example:

public interface CallbackInterface {
    void onCall();
}

and in your PriceListFragment in onCreateView do that:

CallbackInterface callback = new CallbackInterface{
 @Override
  public void onCall() {
     if(itemCart!=null){
       //code to increment badge
     }
  }
};

and pass callback to the adapter's constructor and then use it there.

You can use badge style in TextView now, All you need to do is adjust your textview position to make it look like badge.

        <TextView
                android:id="@+id/fabCounter"
                style="@style/Widget.Design.FloatingActionButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_centerVertical="true"
                android:layout_marginEnd="10dp"
                android:padding="5dp"
                android:text="-9"
                android:textColor="@android:color/black"
                android:textSize="14sp" />

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!