View.findViewById() returning null

2019-06-22 15:07发布

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.

1条回答
倾城 Initia
2楼-- · 2019-06-22 15:34

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!

查看更多
登录 后发表回答