'How to get cart badge in kotlin fragment?

I have already created a custom layout for badge counter and on inflating menu my cart icon is not working my codes are below.

cart Item Layout

<FrameLayout
style="?attr/actionButtonStyle"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:background="?attr/selectableItemBackground"
android:clipToPadding="false"
android:focusable="true">

<ImageView
    android:id="@+id/badge_icon_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:src="@drawable/ic_cart"/>

<TextView
    android:id="@+id/cart_badge_text_view"
    android:layout_width="20dp"
    android:layout_height="20dp"
    android:layout_gravity="right|end|top"
    android:layout_marginEnd="-5dp"
    android:layout_marginRight="-5dp"
    android:layout_marginTop="3dp"
    android:background="@drawable/badge_cart_bg"
    android:gravity="center"
    android:padding="3dp"
    android:textColor="@android:color/white"
    android:text="0"
    android:textSize="10sp"/>

toolbar menu

<item android:id="@+id/cart"
    android:title=""
    app:showAsAction="always"
    app:actionLayout="@layout/custom_cart_item_layout"
    android:icon="@drawable/ic_cart"/>

Code in fragment code



Solution 1:[1]

Try this once-

 override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        ...
        myToolbar.inflateMenu(R.menu.sample_menu)
        myToolbar.setOnMenuItemClickListener {
            when (it.itemId) {
                R.id.action_settings -> {
                    // Navigate to settings screen
                    true
                }
                R.id.action_done -> {
                    // Save profile changes
                    true
                }
                else -> false
            }
        }
    }
}

for more details please find official link

Solution 2:[2]

In the onCreate of your fragment, enable options menu by calling

setHasOptionsMenu(true)

Do this in the fragment's oncreate not in the parent activity

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sandesh KhutalSaheb
Solution 2 return 0