如何在科特林片段中获得购物车徽章?

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

在片段的 onCreate 中,通过调用

启用选项菜单
setHasOptionsMenu(true)

在片段的 oncreate 中而不是在父级中执行此操作 activity

试试这个-

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

更多详情请找官方link