您的位置:首页 > 移动开发 > Android开发

android自定义控件findViewById为空

2014-08-10 23:14 176 查看
今天在做自定义控件findViewById的时候,发现获取的view为空,而其他系统控件获取不为空。后来发现是因为自定义控件的构造函数写的有问题。

错误写法:

public CMapView(Context context) {
super(context);
init(context);
}

public CMapView(Context context, AttributeSet attrs, int defStyle) {
this(context);
}

public CMapView(Context context, AttributeSet attrs) {
this(context);
}

正确写法:

public CMapView(Context context) {
super(context);
init(context);
}

public CMapView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}

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

在自定义控件的时候,复写父控件方法,不能不调用super方法,以为layout内部调用需要初始化super方法里面的内容。

注:另外看到有出现同样问题的原因还有,

1.setContentView在findviewbyId之后调用了

2.没有引用正确的父view。e.g.View container = LayoutInflater.from(context).inflate(resource, root);  view child = container.findviewbyID(); 一定要加上container
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息