如何在 moxy 演示器中获取上下文 android

How to get context in moxy presenter android

如何从 Moxy 演示器获取 activity 上下文? 乍一看很简单……: 1、在MvpView接口中添加Context getMvpActivity ();,在Acivity中实现。 2. 在演示者通话中 getViewState().getMvpActivity().

但是 Moxy 不允许将非 void 方法添加到 MvpView 接口。 请帮助我。

P.S。我需要 Presenter 中的上下文来初始化 App 组件(activitystatic getter 的参数)。

谢谢。抱歉有些语法错误。

通过将 Activity 上下文作为参数添加到 onViewCreated() 中解决了这个问题。 像这样:

//presenter super class
public void onViewCreated (Activity activity) {
    //init component here
    //this.component = ...
    injectPresenter ();
}

protected PresenterComponent getComponent () {
    return this.component;
}

protected abstract void injectPresenter ();



//presenter child class
@Override
public void onViewCreated (Activity activity) {
    super.onViewCreated(this);
}

@Override
protected void injectPresenter () {
    //you can name "inject" different ways
    //in your presenter component interface
    getComponent().inject(this);
}



//activity class
@Override
protected void onCreate () {
    //P.S.(for beginners) variable presenter is the object of class
    //which extends Presenter super class
    presenter.onViewCreated(this);
}

正确的解决方案是不在演示者中使用 activity 上下文。因为,在 activity 重新创建的情况下,此上下文将泄漏(因为演示者仍然活着)。您能够使用应用程序上下文。您可以通过演示者的构造函数传递它。