0

I'm inflating custom layout to menu Up bar to show count in cart item and I achieve with item click. How is it possible to show or set count in menu here? I'm little bit confuse. if its possible then how any idea?

I have tried this

MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.home_screen, menu);
final Menu m = menu;
final MenuItem item = menu.findItem(R.id.nav_cart);

item.getActionView().setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Toast.makeText(HomeScreen.this, "hello", Toast.LENGTH_SHORT).show();
    }
});

custom layout XML. So here I want to set badge count, but how?

file

<RelativeLayout
    android:id="@+id/cart"
    android:layout_width="wrap_content"
    android:layout_marginTop="15dp"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/cart_bag"
        android:layout_width="25dp"
        android:layout_height="25dp"
        app:srcCompat="@drawable/bag" />

    <com.nex3z.notificationbadge.NotificationBadge
        android:id="@+id/badge"
        android:layout_width="20dp"
        android:layout_alignParentTop="true"
        android:layout_alignTop="@id/cart_bag"
        android:layout_height="20dp"
        app:nbBackground="@drawable/badge_bg_with_shadow"
        android:layout_marginLeft="15dp"
        app:nbMaxTextLength="2"/>

</RelativeLayout>

MenuItem

android:id="@+id/nav_cart"
android:orderInCategory="15"
android:title="@string/action_settings"
app:actionLayout="@layout/custom_layout_cart"
app:showAsAction="always"
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
MustafaShaikh
  • 152
  • 2
  • 11

2 Answers2

1

Try to add custom layout programatically..like this

    final MenuItem item = menu.findItem(R.id.nav_cart);
    MenuItemCompat.setActionView(item, R.id.custom_layout_cart);
    actionView = MenuItemCompat.getActionView(item);
    ImageView btn = (ImageView) actionView.findViewById(R.id.cart_bag);
    NotificationBadge count = (TextView) actionView.findViewById(R.id.badge);
    btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Toast.makeText(HomeScreen.this, "hello", Toast.LENGTH_SHORT).show();
    }
});
Prachi Singh
  • 564
  • 3
  • 8
1

Try to set count value to textview from your custom-badge layout.

val tvCartCount = actionView.findViewById(R.id.your_cart_count_id) as TextView

tvCartCount.text = "Your Cart Value"

You can refer this solution for better understanding.

Dhara Vamja
  • 554
  • 4
  • 17