gpt4 book ai didi

java - ImageView 引用和派生类的奇怪行为

转载 作者:行者123 更新时间:2023-12-02 02:08:37 24 4
gpt4 key购买 nike

我在 Android Studio 中创建了一些基于 ConstraintLayout 的自定义组件。首先,我创建了名为 MyButton 的基本抽象类,我在其中执行一些基本操作(例如获取对我的组件的引用)。接下来,我创建了名为 MySpecialButton 的派生类,它扩展了 MyButton,但是当我将 onClickListener 附加到我的 Button(这是我的自定义组件的一部分)并调用修改仅存在于 MySpecialButton 中的元素(引用)的方法时,我的行为很奇怪。

在当前代码中,当我尝试从 onClickListener 调用 setImage() 时,最终会出现日志: E/NULL: ImageView reference is null! 这意味着从 onClickListener 的角度来看,引用 vImageViev 为 null,但它是在 inflateView 调用中初始化的。但是,当我在 inflateView(R.layout.my_special_button) 之后直接从 init() 方法调用 setImage() 时,一切都正常。此外,当我将 protected ImageView vImageView = null; 声明从 MySpecialButton 移动到 MyButton 时,一切都正常。

这是我的 MyButton 类:

public abstract class MyButton extends ConstraintLayout
{
protected Context context = null;

protected View rootView = null;
protected Button vButton = null;
protected Switch vSwitch = null;

public MyButton(Context context)
{
super(context);
this.context = context;
init();
}

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

protected abstract void init();

protected void inflateView(int res)
{
rootView = inflate(context, res, this);

vButton = (Button)rootView.findViewById(R.id.vButton);
vSwitch = (Switch)rootView.findViewById(R.id.vSwitch);
}
}

这是我的 MySpecialButton 类:

public class MySpecialButton extends MyButton
{
protected ImageView vImageView = null;

public MySpecialButton(Context context)
{
super(context);
}

public MySpecialButton(Context context, AttributeSet attr)
{
this(context);
}


@Override
protected void inflateView(int res)
{
super.inflateView(res);

vImageView = (ImageView)rootView.findViewById(R.id.vImageView);
}

protected void init()
{
inflateView(R.layout.my_special_button);

vButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
setImage();
}
});
}

protected void setImage()
{
if(vImageView == null)
Log.e("NULL", "ImageView reference is null!");
else
vImageView.setImageResource(R.drawable.ic_window);
}
}

发生什么事了?我应该做什么才能从 onClickListener 调用 setImage() 而无需空引用?

最佳答案

我认为您在构造函数中执行了错误的 super 调用:

这个

public MySpecialButton(Context context, AttributeSet attr)
{
this(context);
}

应该是:

public MySpecialButton(Context context, AttributeSet attr)
{
super(context, attr);
}

其他类(class)也一样。并将自定义 init 移动到从每个构造函数调用的不同函数中。

关于java - ImageView 引用和派生类的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57341298/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com