2016-05-07 5 views
-1

Ich möchte einige dynamische Text auf Menüelement anzeigen. Das ist bisher mein Code.Null-Zeiger-Ausnahme beim Hinzufügen von Wert auf Menüelement in Android

Menü Datei

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

und in Aktivität

@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; 
} 

Es Nullzeiger-Ausnahmefehler geben in

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

Kann mir jemand helfen, wie ich das beheben kann?

Antwort

0

Ich bin nicht sicher, aber versuchen Sie dies:

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

statt

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

Bitte überprüfen this answer.
Kurz - versuchen Sie app:actionLayout anstelle von android:actionLayout zu verwenden.

Verwandte Themen