使用Mosby实施非ViewGroup MVP Android视图



我正在尝试使用MOSBY实现MVP Android视图(不是活动或片段),但是当在Android适配器中使用视图,并在OnBindViewHolder中访问它时,演示者是目前尚未初始化。看来,直到演示者为null之后,Onattachwindow才被调用。这是我创建的抽象类。

public abstract class MvpImageView<V extends MvpView, P extends MvpPresenter<V>>
    extends AppCompatImageView implements MvpView, ViewGroupDelegateCallback<V, P> {
  protected P presenter;
  protected ViewGroupMvpDelegate<V, P> mvpDelegate;
  private boolean retainInstance = false;
  public MvpImageView(Context context) {
    super(context);
  }
  public MvpImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }
  public MvpImageView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
  }
  /**
   * Get the mvp delegate. This is internally used for creating presenter, attaching and detaching
   * view from presenter etc.
   *
   * <p><b>Please note that only one instance of mvp delegate should be used per android.view.View
   * instance</b>.
   * </p>
   *
   * <p>
   * Only override this method if you really know what you are doing.
   * </p>
   *
   * @return {@link ViewGroupMvpDelegate}
   */
  @NonNull protected ViewGroupMvpDelegate<V, P> getMvpDelegate() {
    if (mvpDelegate == null) {
      mvpDelegate = new ViewGroupMvpDelegateImpl<>(this, this, true);
    }
    return mvpDelegate;
  }
  @Override protected void onAttachedToWindow() {
    super.onAttachedToWindow();
    Log.d(getClass().getName(), "Attaching to Window");
    getMvpDelegate().onAttachedToWindow();
  }
  @Override protected void onDetachedFromWindow() {
    super.onDetachedFromWindow();
    Log.d(getClass().getName(), "Detaching from Window");
    getMvpDelegate().onDetachedFromWindow();
  }
  @SuppressLint("MissingSuperCall") @Override protected Parcelable onSaveInstanceState() {
    return getMvpDelegate().onSaveInstanceState();
  }
  @SuppressLint("MissingSuperCall") @Override
  protected void onRestoreInstanceState(Parcelable state) {
    getMvpDelegate().onRestoreInstanceState(state);
  }
  /**
   * Instantiate a presenter instance
   *
   * @return The {@link MvpPresenter} for this view
   */
  public abstract P createPresenter();
  @Override public P getPresenter() {
    return presenter;
  }
  @Override public void setPresenter(P presenter) {
    this.presenter = presenter;
  }
  @Override public V getMvpView() {
    return (V) this;
  }
  @Override public final Parcelable superOnSaveInstanceState() {
    return super.onSaveInstanceState();
  }
  @Override public final void superOnRestoreInstanceState(Parcelable state) {
    super.onRestoreInstanceState(state);
  }
}

这是基于Mvplinearlayout实现的。过去,我已经使用了另一个MVP库,称为Moxy,它具有用于Oncreate和Onattachtowindow的代表方法。

我可以添加一个初始化例程,该例程可致电getMvpdelegate()。关于在OnBindViewHolder和RecyClerview中使用时如何使此工作的任何想法?

不要在适配器中使用MVP。它只是使事情变得过于复杂且繁琐。

示例:可以回收视图/视图持有人,也应该回收演示者吗?如果是,您如何实施并确保内部演示者是新鲜的?您如何在滚动时查看演示者?如果您的Adapterset更改了怎么办?屏幕方向更改呢?

根本不这样做。

最新更新