非静态块中的 init 方法 Android
init method in non-static block Android
我正在扩展 ScrollView,因为我在构造函数之后使用了非静态块来初始化一些变量。
代码
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) 方法。这就是为什么我使用非静态块。您能否建议这是否是正确的做法?
*我能够运行这段代码没有任何错误。
您不能使用静态上下文。如果您的问题是您不想在每个构造函数中调用 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);
}
我正在扩展 ScrollView,因为我在构造函数之后使用了非静态块来初始化一些变量。
代码
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) 方法。这就是为什么我使用非静态块。您能否建议这是否是正确的做法?
*我能够运行这段代码没有任何错误。
您不能使用静态上下文。如果您的问题是您不想在每个构造函数中调用 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);
}