我想获取菜单视图,但出现此错误:
试图调用虚拟方法'android.view.View 空对象引用上的android.view.View.findViewById(int)'
请帮助。
活动:
@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_action_bar, menu);
View view2 = menu.findItem(R.id.cart_menu).getActionView();
badge = (NotificationBadge)view2.findViewById(R.id.badge);
cart_icon = (ImageView)view2.findViewById(R.id.cart_icon);
cart_icon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(HomeActivity.this, "Test", Toast.LENGTH_SHORT).show();
}
});
myFunction();
return true;
}
menu_action_bar.xml
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
<item
android:id="@+id/cart_menu"
android:icon="@drawable/ic_shopping_cart_black_24dp"
android:title="Panier"
app:showAsAction="always"
android:actionLayout="@layout/action_bar_notification_icon" />
action_bar_notification.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
style="@android:style/Widget.ActionButton">
<ImageView
android:id="@+id/cart_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_shopping_cart_black_24dp"/>
<com.nex3z.notificationbadge.NotificationBadge
android:id="@+id/badge"
android:layout_width="28dp"
android:layout_height="28dp"
android:layout_toRightOf="@+id/cart_icon"
android:layout_alignParentTop="@+id/cart_icon"
android:layout_marginLeft="-10dp"
android:layout_marginTop="-10dp"
app:nbMaxTextLength="2"
/>
答案 0 :(得分:0)
似乎onCreateOptionsMenu
内的布局尚未膨胀。因此,您需要在onPrepareOptionsMenu
内部扩大自定义视图。像这样:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_action_bar, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
Menu menuChart = menu.findItem(R.id.cart_menu);
FrameLayout rootView = (FrameLayout) menuChart.getActionView();
mNbBadge = (NotificationBadge) rootView.findViewById(R.id.badge);
mImvCartIcon = (ImageView) rootView.findViewById(R.id.cart_icon);
// add the listener or anything related
return true;
}