作者:mobiledu2502915233 | 来源:互联网 | 2022-12-10 11:27
我有一个从XML加载的活动,其中的视图具有通常的ID:
我试图在代码中引用三个视图:
public ItemViewHolder(View itemView) {
super(itemView);
nameView = itemView.findViewById(R.id.nameView);
priceView = itemView.findViewById(R.id.priceView);
imageView = itemView.findViewById(R.id.imageView);
}
nameView
并且priceView
被正确引用,但是imageView
没有被引用,并且是null
:
为什么我不能参考imageView
?
(如果我遍历视图树,它就在那里.)
更新:我同时执行了Clean Project和Invalidate Caches/Restart,问题仍然存在.
更新2: ItemViewHolder
源自RecyclerView.ViewHolder
.CircleImageView
源自FrameLayout
(不 ImageView
).这个XML是我的视图持有者的布局.
更新3:这是我的圈子视图的构造函数:
public class CircleImageView extends FrameLayout {
public CircleImageView(Context context) {
super(context);
init();
}
public CircleImageView(Context context, AttributeSet attrs) {
super(context);
init();
}
public CircleImageView(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
...
}
此外,正如Subzero所指出的,我已经检查了mID
视图的ID属性(字段),而-1
这似乎是导致问题的原因.我不知道为什么它是-1.
1> Mike M...:
super
将双参数构造函数中的调用更改为:
super(context, attrs);
当a View
从布局中膨胀时,XML属性及其值将通过以下方式传递给双参数构造函数AttributeSet
.如果您没有将它传递给超类,那么id
您在XML中指定的内容永远不会被设置View
,因此findViewById()
无法使用给定的ID找到它.