view的三个构造方法与findViewById()结果为null的关系?

在Activity的onCreateView 中,有时候发现写的自定义view,通过 findViewById 返回为Null,导致空指针异常。


布局文件中定义

    <com.example.qqmediaplayer.view.LyricsView
        android:background="@drawable/base_bg"
        android:id="@+id/lyricsview"
        android:layout_width="wrap_content"
        android:layout_height="@dimen/lyricsview_height" >
    </com.example.qqmediaplayer.view.LyricsView>


在生成该view的时候,会执行LyricsView的2个参数的构造方法。

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



如果 这个时候 这么定义


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

findViewById 为null, 造成空指针异常 。但是view可以正常显示。

如果 这么写


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

调用3个参数的构造方法,就没事。


-----------------------------------------

既然view显示,就说明对象已经创建。

猜想调用一个参数的构造方法,创建对象并不是在setContentView之后,因此导致 findViewById 为null? 貌似不对,因为在onClick事件中findViewById 还是null,

因此 调用一个参数构造方法生成的view并不是在DecorView中?


   public View findViewById(int id) {
        return getWindow().findViewById(id);
    }
   

   public View findViewById(int id) {
        return getDecorView().findViewById(id);
    }









  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值