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 方法解决见: 点击打开链接


 


     

更多相关文章

  1. Android 获取蓝牙Mac地址的正确方法
  2. 分析方法论探讨
  3. android 程序开发的插件化 模块化方法 之二
  4. 关于“Android SDK manager中不出现完整Android版本安装包列表”
  5. Android关于apk版本更新方法
  6. Android之gallery 常见2种使用方法和3D效果总结

随机推荐

  1. 史上最详细的Android系统SystemUI 启动过
  2. Kotlin 概览——如何看待 Google 将 Kotl
  3. [Android] [ Android启动流程 ] [ 下 ] [
  4. android之组件2
  5. Android监听网络变化 二
  6. Android(安卓)Studio使用smack进行ejabbe
  7. 利用Android Studio、MAT对Android进行内
  8. android进程和应用程序的生命周期
  9. 初试Kotlin-使用Kotlin运行Android的第一
  10. Android SharedPreferences 存储复杂对象