View.findViewById() returning null

邮差的信 提交于 2019-12-23 12:17:30

问题


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:


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!



来源:https://stackoverflow.com/questions/13415556/view-findviewbyid-returning-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!