androidの自定义控件View在Activity中使用findByViewId得到结果为null,解决方法。。
16lz
2021-01-23
androidの自定义控件View在Activity中使用findByViewId得到结果为null
1. 大家常常自定义view,,然后在xml 中添加该view 组件。。如果在Activity 中使用findByViewId 方法获取该view 时候,返回对象总为空 。。。 xml 代码
java代码 View rootView = View.inflate(this, R.layout.frag_shandina, null); setContentView(rootView); setContentView(rootView); view = (CustomSurfaceView)findViewById(R.id.customsufaceview); LogUtils.i("blueberry", "view="+view);
打印结果总是为 null ,, 总是报空指针错误。。。 其实问题还是出现在,,,自定义view 中,构造方法。。
解决方法:
错误写法: public CustomSurfaceView(Context context, AttributeSet attrs) {
super(context);
正确写法:
public CustomSurfaceView(Context context, AttributeSet attrs) {//注意这里容易引起空指针异常的。。。。。super(context,attrs);
这种初始化对象,会调用这个构造方法,,因为调用父类的构造函数没有传入AttributeSet , 或者 CustomSurfaceView view = new CustomSurfaceView(this, null);
setContentView(view );
这种方式添加进行初始化。。
更多详情自定义view 方法解决见: 点击打开链接
更多相关文章
- Android 获取蓝牙Mac地址的正确方法
- 分析方法论探讨
- android 程序开发的插件化 模块化方法 之二
- 关于“Android SDK manager中不出现完整Android版本安装包列表”
- Android关于apk版本更新方法
- Android之gallery 常见2种使用方法和3D效果总结