簡體   English   中英

非靜態塊Android中的init方法

[英]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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM