今天测试,发现自己写的自定义控件通过findViewById(R.id.data_ad_banner);
获取不到,为null
报错如下
最终发现是因为,在自定义控件中,设置了id
,去掉就可以了。
这里总结了一些findViewById
是Null
的常见解决方案:
1、必须实现以下方法。
public View(Context context, AttributeSet attrs) {
super(context, attrs);
}
public View(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
2、A.findViewById(B)
,判断控件(id为B)是否在A布局里面。
3、在自定义View中,不要调用setId(int id)
方法给View设置id
。