ToolBar MenuItem error

感情迁移 提交于 2019-12-11 13:38:39

问题


I am trying to set Cart Basket icon for Add To Cart functionality. While I run the app I got this error

Attempt to invoke virtual method 'android.view.View android.widget.RelativeLayout.findViewById(int)' on a null object reference

Here I am using AppCompatActivity.

My code is here: MainActivity.java

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
         getMenuInflater().inflate(R.menu.main, menu);
        RelativeLayout badgeLayout = (RelativeLayout) menu.findItem(R.id.badge).getActionView();
        mCounter = (TextView) badgeLayout.findViewById(R.id.counter);
        return true;
}

menu.xml:

<item
    android:id="@+id/badge"
    android:actionLayout="@layout/badge_layout"
    android:title="Badges"
    app:showAsAction="always">
</item>

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

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:clickable="true"
            android:src="@drawable/ic_shopping_cart"/>

        <TextView
            android:id="@+id/counter"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:padding="8dp"
            android:text="12"
            android:textSize="10sp"
            android:textColor="@color/colorPrimary" />
    </RelativeLayout>

回答1:


Finally Got the cart icon. Replace this

  <item
            android:id="@+id/badge"
            android:actionLayout="@layout/badge_layout"  //Check this LINE
            android:title="Badges"
            android:actionViewClass="android.widget.RelativeLayout"
            app:showAsAction="always">
        </item>

To

<item
        android:id="@+id/badge"
        app:actionLayout="@layout/badge_layout"  //Check this LINE(Changes made here)
        android:title="Badges"
        android:actionViewClass="android.widget.RelativeLayout"
        app:showAsAction="always">
    </item>


来源:https://stackoverflow.com/questions/35622418/toolbar-menuitem-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!