I have this code:
private void inflateMenu() {
if (menu == null) {
mFanView = (LinearLayout) findViewById(R.id.fanView);
final View v = LayoutInflater.from(getContext()).inflate(
R.layout.sidemenu, mFanView);
menu = (MenuView) v.findViewById(R.id.listViewMenu);
}
menu.setColors(backgroundColor, selectedColor, unselectedColor);
}
When debugging, v contains a MenuView whose id equals R.id.listViewMenu + 1
. Of course this will throw a NPE on menu.setColors.
Why does R.id.listViewMenu contain an ID that doesn't lead to the view with that ID in XML?
I've tried to clean my project but it still stays the same.
EDIT: Posting requested files.
sidemenu.xml
<com.ui.library.slidingmenu.MenuView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/listViewMenu"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
EDIT: Problem solved.
To anyone coming here because findViewById returns null: Clean the project. If it doesn't work, clean the project again. If it doesn't work, clean ALL your projects. Until it works. If it doesn't work, then ask.
FindViewById can be null if you call the wrong super constructor in a custom view. The ID tag is part of attrs, so if you ignore attrs, you delete the ID.
findViewById returns an instance of View , which is then cast to the target class. All good so far. To setup the view, findViewById constructs an AttributeSet from the parameters in the associated XML declaration which it passes to the constructor of View . We then cast the View instance to Button .
findViewById(R. id. some_id) to retrieve Views in code. ViewBinding works similarly, but, in addition to just adding the IDs into a global list, it parses more information from XML and generates code for each layout file.
view. findViewById() is used to find a view inside a specific other view. For example to find a view inside your ListView row layout.
Try this:
(In eclipse menu bar) Project > Clean
Explanation: sometimes during building, the R.java class messes up and causes wrong references to id's. Sometimes when I compile, an image suddenly changes because the id associated with it is changed too. This can happen with any resource, Layouts, Id's, etc.
A way to regenerate the R.java class and fix irregularities is by cleaning your project.
Hope that helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With