1.最近在写一个小app,在一个java class中,以LayoutInflater.from(context).inflate(R.layout.item, this, false);的方式去加载布局,当我准备找到布局中的某个控件时,比如imageView,假设其id为iv_pic
private ImageView mIvIcon;
private View mView;
在自定义的init()方法中获取imageView
一开始是这样子写的
private void init(Context context){
...
mView = LayoutInflater.from(context).inflate(R.layout.item, this, false);
mIvIcon = findViewById(R.id.iv_pic);
...
}
结果运行之后出错了,设置断点之后debug,当运行到这里的时候,发现mIvIcon竟然为null!!!!
后来才明白在activity中直接调用findViewById方法,它的完整形式是this.findViewById(),但是我写的这个java class显然到目前为止还没有绑定view鸭!!
所以正确的写法应该是
private void init(Context context){
...
mView = LayoutInflater.from(context).inflate(R.layout.item, this, false);
mIvIcon = mView.findViewById(R.id.iv_pic);
...
}