-1

I want to display some dynamic text on menu item. This is my code so far.

Menu file

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MyActivity">

<item
    android:id="@+id/search"
    android:title="Search"
    android:icon="@drawable/magnify"
    app:showAsAction="ifRoom"/>

<item
    android:id="@+id/Cart"
    android:title="Cart"
    android:icon="@drawable/cart"
    app:showAsAction="ifRoom"/>

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


</menu>

actinbar_badge_layout.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="48dp"
    android:layout_height="fill_parent"
    android:layout_gravity="right" >

    <!-- Menu Item Image -->
    <ImageView
        android:layout_width="48dp"
        android:layout_height="fill_parent"
        android:clickable="true"
        android:src="@drawable/cart" />

    <!-- Badge Count -->
    <TextView
        android:id="@+id/actionbar_notifcation_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:padding="4dp"
        android:text="99"
        android:textColor="#FF0000" />

</RelativeLayout>

and in Activity

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_my2, menu);
    RelativeLayout badgeLayout = (RelativeLayout) menu.findItem(R.id.badge).getActionView();

    TextView tv = (TextView) badgeLayout.findViewById(R.id.actionbar_notifcation_textview);
    tv.setText("12");
    return true;
}

It is giving null pointer exception error in

TextView tv = (TextView) badgeLayout.findViewById(R.id.actionbar_notifcation_textview);

Can anyone help me on how to fix this?

Tal Avissar
  • 10,088
  • 6
  • 45
  • 70
Devesh Agrawal
  • 8,982
  • 16
  • 82
  • 131

2 Answers2

0

I am not sure but try this:

TextView tv = (TextView) menu.findViewById(R.id.actionbar_notifcation_textview);

instead

TextView tv = (TextView) badgeLayout.findViewById(R.id.actionbar_notifcation_textview);
Pranita
  • 803
  • 7
  • 16
0

Please check this answer.
Briefly - try to use app:actionLayout instead of android:actionLayout.

Community
  • 1
  • 1
Goltsev Eugene
  • 3,325
  • 6
  • 25
  • 48