findViewById返回null的诡异情况

来源:互联网 发布:数据库设计各阶段任务 编辑:程序博客网 时间:2024/05/21 23:33

在将自定义组件加入到xml后,在相应的activity中调用,发现findViewById取组件一直返回空值。网上大抵的说法都是需要在setContentView()之后,或者说要加入资源文件,反复检查确认没错。调试了半天,后来才发现一个小错误,鉴于在网络上未发现有人数过,所以在这里写下来:


对于一个自定义view,比如:

public class CustomView extends RelativeLayout {

    public CustomView (Context context) {
        super(context);

    }

    public CustomView (Context context, AttributeSet attrs) {
        super(context, attrs);

    }

}

构造方法大致是这样,一般的话,如果view要加入到xml中而不是运行时添加到话,那么就需要使用到带有AttributeSet 的构造方法。

出现findViewById返回null值的地方就在第二个构造方法中,我写成了:

    public CustomView (Context context, AttributeSet attrs) {
        super(context);
    }

少了一个attrs。

希望看到这篇文章的同学检查检查下


原创粉丝点击