Home > OS >  How to get cart badge in kotlin fragment?
How to get cart badge in kotlin fragment?

Time:05-11

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

CodePudding user response:

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

CodePudding user response:

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

  • Related