FindViewById returns null when searching for items in the action bar on Android 3.2.

I am working on an application that uses a custom action bar layout referenced via android:actionBarStyle and android:customNavigationLayout in themes.xml . The panel has several elements, for example, a reset button and some information. On android 4 devices, these buttons can be found via findViewById (inside the action), but on android 3.2 findViewById returns null . Then it throws a NullPointerException.

Application uses ActionbarSherlock 4.2.0

Here is the .xml theme:

  <style name="Theme.SRF.Tablet" parent="style/Theme.Sherlock"> <item name="android:windowContentOverlay">@drawable/header_shadow</item> <item name="android:actionBarStyle">@style/TTTActionBar</item> </style> <style name="TTTActionBar" parent="style/Widget.Sherlock.ActionBar"> <item name="android:background">@drawable/bg_header</item> <item name="android:customNavigationLayout">@layout/actionbar_custom</item> </style> 

Activity:

  @Override protected void onCreate(Bundle _savedInstanceState) { setContentView(...); // next line throws NullPointerException on android 3.2 findViewById(R.id.actionbar_custom_bt_refresh).setOnClickListener(mClickListener); .... } 
+6
source share
2 answers

I don't know if this will help you, but from here :

Try adding:

 <item name="customNavigationLayout">@layout/custom_action</item> 

to go along with:

 <item name="android:customNavigationLayout">@layout/custom_action</item> 
+6
source

In onCreate views are not guaranteed, but you need to wait until onCreateView or even onActivityCreated is safe. Usually onCreateView is fine, but it is always useful to do a null check in the view just in case.

onCreate

Note that this can be triggered while fragment activity is still in the creation process. Thus, you cannot rely on such things as the hierarchy of representing the contents of the activity is initialized at this moment. If you want to do the work after creating the activity itself, see onActivityCreated (Bundle).

onCreateView

Called for the fragment to instantiate its user interface. This is optional, and non-graphical fragments can return null (which is the default). This will be called between onCreate (Bundle) and onActivityCreated (Bundle).

If you return the view from here, you will later be called in onDestroyView () when the view is released.

onActivityCreated

Called when a fragment activity has been created, and this is an instance of the fragment instance view. It can be used for final initialization when these parts are in place, for example, retrieving views or restoring state. It is also useful for fragments that use setRetainInstance (boolean) to save their instance, as this callback tells the fragment when it is fully associated with the new example action. This is called after onCreateView (LayoutInflater, ViewGroup, Bundle) and before onViewStateRestored (Bundle).

+2
source

All Articles