![](/img/trans.png)
[英]Calling a non-static method in an android OnPreferenceClickListener
[英]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.