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
错误写法:
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
相关文章推荐
- Android 自定义控件布局 NullPointerException findViewById
- android开发之自定义控件时findViewById方法返回null的解决方法
- Android Error —— 自定义控件FindViewById() 返回 Null
- android:通过findViewById试图获取界面元素对象为Null,运行会提示空指针异常
- [Android] setContentView和inflater区别以及findViewById和inflater的区别
- Android通过findViewById()获取控件为NULL
- [转]Jollen 的 Android 教學,#6: WebView 體驗與 findViewByID
- [Android-Tips] findviewbyid function returns null
- android中布局文件中的控件通过findviewbyid无法关联的解决方法
- android findViewById
- Android扩展:一个自动findViewById的小工具
- inflate, findViewById与setContentView的区别与联系 分类: H1_ANDROID 2014-04-18 22:54 1119人阅读 评论(0) 收藏
- [Android] ExpandableListActivity使用findViewById查找child中view的时序问题
- android中findViewById(R.id.XXX)提示空指针异常NullPointerException的原因
- 关于android findViewById 返回为空问题
- Android application - findViewById返回NULL的问题
- android中调用findViewById时出现:java.lang.NullPointerException
- 求助 android开发中 如果两个控件的id相同 会怎样?如何使用findviewbyid ()寻找到?
- android findViewById 返回 null
- 【android中findViewById返回控件指针为NULL】