I am extending ScrollView and in that i have used non-static block after constructors to initialize some of the variables.
Code
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());
}
I don't want to call init(context) method in each constructor. Thats why i have used non-static block. Can you please suggest if this is the correct way of doing it?
*I am able to run this code without any error.
you can't use the static context. If your problem is the fact that you don't want to call init in each constructor just use this
instead of super
(explicit constructor invocation). Eg
public ScrollViewExtended(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ScrollViewExtended(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(this);
}