gpt4 book ai didi

java - Android 非静态 block 中的 init 方法

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

我正在扩展 ScrollView,因为我在构造函数之后使用了非静态 block 来初始化一些变量。

代码

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

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

public ScrollViewExtended(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public ScrollViewExtended(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}

private void init(Context context) {
activity = (Activity) context;
userActivityLogDao = new UserActivityLogDao();
activity_name = activity.getClass().getSimpleName();
}

{
init(getContext());
}

我不想在每个构造函数中调用 init(context) 方法。这就是我使用非静态 block 的原因。您能否建议这是否是正确的做法?

*我能够运行此代码,没有任何错误。

最佳答案

您不能使用静态上下文。如果您的问题是您不想在每个构造函数中调用 init,只需使用 this 而不是 super (显式构造函数调用) 。例如

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

public ScrollViewExtended(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(this);
}

关于java - Android 非静态 block 中的 init 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50388737/

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