0

У меня есть TextView, работающий в качестве значка уведомления по элементу меню. Проблема заключается в том, что метод findViewById всегда возвращает null после изменения ориентации, поэтому, когда я пытаюсь изменить его видимость с помощью setVisibility, он выдает исключение NullPointerException. Я попробовал снова вызвать onCreateOptionsMenu, вызвав invalidateOptionsMenu в onRestart, но он, похоже, не помогает.TextView в меню всегда имеет значение null после изменения ориентации

Из того, что я могу сказать, каждый другой вид найден, и именно этот TextView является неприятностью.

часть, где он выходит из строя (это называется в OnCreate):

public void updateUnreadNotificationCount(final int unreadNotificationsCount) { 
    unreadNotificationCount = unreadNotificationsCount; 
    if (unreadNotificationCount == 0) { 
     notificationCounter.setVisibility(View.INVISIBLE); 
    }else { 
     notificationCounter.setVisibility(View.VISIBLE); 
     notificationCounter.setText(String.valueOf(unreadNotificationCount)); 
    } 
} 

Как TextView получает создан:

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.main, menu); 

    View count = menu.findItem(R.id.action_notifications).getActionView(); 
    notificationCounter = (TextView) count.findViewById(R.id.textview_notification_count); 
    count.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      Intent i = new Intent(mCtx, NotificationListActivity.class); 
      startActivity(i); 
     } 
    }); 
    notificationCounter.setText(String.valueOf(unreadNotificationCount)); 
    return super.onCreateOptionsMenu(menu); 
} 

XML, для пункта меню:

<item 
    android:id="@+id/action_notifications" 
    android:title="@string/action_notifications" 
    android:icon="@drawable/ic_mail_white_48dp" 
    android:actionLayout="@layout/actionbar_notification_icon" 
    android:showAsAction="always" 
    app:showAsAction="always" 
    android:orderInCategory="60"/> 

Схема действий для TextView:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:clickable="true" 
      style="@android:style/Widget.ActionButton"> 

<ImageView 
    android:id="@+id/imageview_notification" 
    android:src="@drawable/ic_mail_white_48dp" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:gravity="center" 
    android:layout_margin="0dp"/> 

<TextView xmlns:android="http://schemas.android.com/apk/res/android" 
      android:id="@+id/textview_notification_count" 
      android:layout_width="wrap_content" 
      android:minWidth="17sp" 
      android:textSize="12sp" 
      android:textColor="#ffffffff" 
      android:layout_height="wrap_content" 
      android:gravity="center" 
      android:text="@null" 
      android:layout_alignTop="@id/imageview_notification" 
      android:layout_alignRight="@id/imageview_notification" 
      android:layout_marginRight="0dp" 
      android:layout_marginTop="3dp" 
      android:paddingBottom="1dp" 
      android:paddingRight="4dp" 
      android:paddingLeft="4dp" 
      android:background="@drawable/rounded_square"/> 

</RelativeLayout> 

ответ

0

Успели решить проблему, переместив инициализацию TextView в onPrepareOptionsMenu и вызов invalidateOptionsMenu() во onResume().