简体   繁体   English

View.findViewById()返回null

[英]View.findViewById() returning null

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 . 调试时,v包含一个id等于R.id.listViewMenu + 1的MenuView。 Of course this will throw a NPE on menu.setColors. 当然这会在menu.setColors上抛出一个NPE。

Why does R.id.listViewMenu contain an ID that doesn't lead to the view with that ID in XML? 为什么R.id.listViewMenu包含的ID不会导致XML中带有该ID的视图?

I've tried to clean my project but it still stays the same. 我试图清理我的项目,但它仍然保持不变。

EDIT: Posting requested files. 编辑:发布请求的文件。

sidemenu.xml 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. 对于因为findViewById返回null而来到这里的任何人:清理项目。 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. 如果它不起作用,那么问。

Try this: 试试这个:

(In eclipse menu bar) Project > Clean (在eclipse菜单栏中)Project> Clean

Explanation: sometimes during building, the R.java class messes up and causes wrong references to id's. 说明:有时在构建期间,R.java类会混淆并导致对id的错误引用。 Sometimes when I compile, an image suddenly changes because the id associated with it is changed too. 有时当我编译时,图像会突然改变,因为与之关联的id也会改变。 This can happen with any resource, Layouts, Id's, etc. 任何资源,布局,ID等都可能发生这种情况。

A way to regenerate the R.java class and fix irregularities is by cleaning your project. 重新生成R.java类并修复不规则性的方法是清理项目。

Hope that helps! 希望有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM