itslonua
10/23/2017 - 5:04 PM

AccountHolder.java

/**
 * Date: 15.11.2016
 * Time: 9:41
 *
 * @author Savin Mikhail
 */
public abstract class MvpViewHolder extends RecyclerView.ViewHolder {
	private MvpDelegate mMvpDelegate;
	private final MvpDelegate mParentDelegate;
	public MvpViewHolder(MvpDelegate<?> parentDelegate, final View itemView) {
		super(itemView);
		ButterKnife.bind(this, itemView);
		mParentDelegate = parentDelegate;
	}
	@Nullable
	protected MvpDelegate getMvpDelegate() {
		if (getMvpChildId() == null) {
			return null;
		}
		if (mMvpDelegate == null) {
			mMvpDelegate = new MvpDelegate<>(this);
			mMvpDelegate.setParentDelegate(mParentDelegate, getMvpChildId());
		}
		return mMvpDelegate;
	}
	protected void destroyMvpDelegate() {
		if (getMvpDelegate() != null) {
			getMvpDelegate().onSaveInstanceState();
			getMvpDelegate().onDetach();
			mMvpDelegate = null;
		}
	}
	protected void createMvpDelegate() {
		if (getMvpDelegate() != null) {
			getMvpDelegate().onCreate();
			getMvpDelegate().onAttach();
		}
	}
	protected abstract String getMvpChildId();
} 

class AccountHolder extends MvpViewHolder implements AccountView {
	@InjectPresenter
	AccountPresenter mAccountPresenter;

	/**
	@BindView(R.id.item_account_check_box)
	CheckBox mCheckBox;
	...
	**/
	
	private Account mAccount;
	
	AccountHolder(View itemView) {
		super(mParentDelegate, itemView);
	}
	
	@ProvidePresenter
	AccountPresenter provideAccountPresenter() {
		return new AccountPresenter(mAccount.getCode());
	}
	
	// Call from onBindViewHolder
	public void setAccount(Account account) {
		destroyMvpDelegate();
		
		mAccount = account;
		
		createMvpDelegate();
		
		itemView.setOnClickListener(view -> mAccountsPresenter.onAccountClick(account));
	}
	
	// Critical! Return this item unique id
	@Override
	protected String getMvpChildId() {
		return mAccount == null ? null : mAccount.getId();
	}
	
	// implement acccount veiw
}