我正在尝试用Mosby实现一个MVP Android View (而不是activity或fragment),但是当在Android Adaptor中使用视图,并在onBindViewHolder中访问它时,presenter此时不会初始化。似乎直到onBindViewHolder完成后才调用onAttachWindow,因为presenter为空。下面是我创建的抽象类。
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库,它既有onAttachToWindow的委托方法,也有onCreate的委托方法。
我可以在构造函数中添加一个调用getMvpDelegate().onAttachWindow的初始化例程,但这看起来更像是一个hack。对于在onBindViewHolder和RecyclerView中使用时如何让它工作,有什么想法吗?
https://stackoverflow.com/questions/47715948
复制相似问题