我正在尝试使用 Mosby 实现 MVP Android 视图(不是活动或片段),但是当在 Android 适配器中使用该视图并在 onBindViewHolder 中访问它时,此时演示者未初始化。似乎直到 onBindViewHolder 完成后才调用 onAttachWindow,因为演示者为 Null。这是我创建的抽象类。
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 实现的。我过去使用过另一个名为 Moxy 的 MVP 库,它具有 onCreate 和 onAttachToWindow 的委托方法。
我可以在构造函数中添加一个调用 getMvpDelegate().onAttachWindow 的初始化例程,但这似乎更像是一种黑客攻击。在 onBindViewHolder 和 RecyclerView 中使用时如何使其工作的任何想法?