如何在方法中正确发送上下文、活动和接口连接



我有这个方法:

    public LeftDrawerView(Activity activity, Context context, LeftDrawerViewInterface delegate)
{
   this.activity = activity;
   this.context = context;
   this.delegate = delegate;
}

要调用上面的方法,我使用以下方法调用:

LeftDrawerView leftDrawerView new LeftDrawerView(this, this, this);

以后可能会感到困惑,我想简化一下,有什么办法可以做到这一点吗?

我可以像这样调用单个变量:

LeftDrawerView leftDrawerView new LeftDrawerView();
leftDrawerView.context = this;
leftDrawerView.activity = this;
leftDrawerView.delegate = this;

这更具可读性,但要执行的代码更多。 想要避免这种情况。 任何建议将不胜感激。

你可以再创建一个构造函数来调用你现有的构造函数:

public LeftDrawerView(Activity from) {
  this(from, from, from);
}

像这样传递您的自定义活动不是更容易吗:

public LeftDrawerView(CustomActivity customActivity){
   this.customActivity = customActivity;
}

而且,如果你需要的话,就这样投射:

((Activity) LeftDrawerView.this.customActivity);
((Context) LeftDrawerView.this.customActivity);
((LeftDrawerViewInterface) LeftDrawerView.this.customActivity);

这样做怎么样:

public LeftDrawerView () {};

然后,您将创建适当的资源库:

public void setActivity(Activity activity) {...};

最后是合适的获取者:

public Activity getActivity() {...};
public Context getContext() {...};
public LeftDrawerViewInterface getLeftDrawerViewInterface() {...};

您将使用单个属性来存储Activity实例,然后在每个 getter 上执行正确的转换。

最新更新