android 自定义控件View在Activity中使用findByViewId得到结果为null
2017-01-13 12:05
856 查看
转载:http://blog.csdn.net/xiabing082/article/details/48781489
1. 大家常常自定义view,,然后在xml 中添加该view 组件。。如果在Activity 中使用findByViewId 方法获取该view 时候,返回对象总为空 。。。 xml 代码<com.infzm.slidingmenu.demo.view.CustomSurfaceView android:id="@+id/customsufaceview" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="6" />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 );这种方式添加进行初始化。。
相关文章推荐
- androidの自定义控件View在Activity中使用findByViewId得到结果为null,解决方法。。
- Android使用Fragment,不能得到Fragment内部控件,findViewById()结果是Null--已经解决
- Android使用Fragment,不能得到Fragment内部控件,findViewById()结果是Null--已经解决
- Android基于4.4以上沉侵式状态栏和继承BaseActivity不用findViewbyid得到控件id
- android getActivity.findViewById获取ListView 返回NULL
- android getActivity.findViewById获取ListView 返回NULL的方法
- Android中使用findViewByMe提升组件查找效率
- 关于android Activity中注解的使用,省去无用的findviewbyid....setonclick.....
- android开发之自定义控件时findViewById方法返回null的解决方法
- android 使用Tabhost 发生could not create tab content because could not find view with id 错
- Android中使用findViewByMe提升组件查找效率
- android 使用Tabhost 发生could not create tab content because could not find view with id 错...
- [Android] android.app.Activity.findViewById(int) on a null object reference
- 在自定义控件的过程中犯下的错,在调用有三个参数的构造方法时this(context,null,0);第二个参数为空,在Activity中 findViewById找到对应的控件时
- Android 自定义控件布局 NullPointerException findViewById
- 求助 android开发中 如果两个控件的id相同 会怎样?如何使用findviewbyid ()寻找到?
- [Android] ExpandableListActivity使用findViewById查找child中view的时序问题
- Android Error —— 自定义控件FindViewById() 返回 Null
- android 使用Tabhost 发生could not create tab content because could not find view with id 错...
- Android使用TabHost程序异常终止could not create tab content because could not find view with id 错误