Skip to content

CustomView as MvpView

Yuri Shmakov edited this page Aug 15, 2017 · 4 revisions

CounterPresenter.java:

@InjectViewState
public class CounterPresenter extends MvpPresenter<CounterView> {
	private int mCount;

	public CounterPresenter() {
		getViewState().showCount(mCount);
	}

	public void onPlusClick() {
		mCount++;
		getViewState().showCount(mCount);
	}
}

CounterView.java:

public interface CounterView extends MvpView {
	@StateStrategyType(AddToEndSingleStrategy.class)
	void showCount(int count);
}

CounterWidget.java

public class CounterWidget extends FrameLayout implements CounterView {

	private MvpDelegate mParentDelegate;
	private MvpDelegate<CounterWidget> mMvpDelegate;

	@InjectPresenter
	CounterPresenter mCounterPresenter;
	private TextView mCounterTextView;

	public CounterWidget(Context context, AttributeSet attrs) {
		super(context, attrs);
		LayoutInflater.from(context).inflate(R.layout.item_counter, this, true);
		mCounterTextView = (TextView) findViewById(R.id.count_text);
		View button = findViewById(R.id.plus_button);
		button.setOnClickListener(view -> mCounterPresenter.onPlusClick());
	}

	public void init(MvpDelegate parentDelegate) {
		mParentDelegate = parentDelegate;

		getMvpDelegate().onCreate();
		getMvpDelegate().onAttach();
	}

	@Override
	protected void onDetachedFromWindow() {
		super.onDetachedFromWindow();

		getMvpDelegate().onSaveInstanceState();
		getMvpDelegate().onDetach();
	}

	public MvpDelegate<CounterWidget> getMvpDelegate() {
		if (mMvpDelegate != null) {
			return mMvpDelegate;
		}

		mMvpDelegate = new MvpDelegate<>(this);
		mMvpDelegate.setParentDelegate(mParentDelegate, String.valueOf(getId()));
		return mMvpDelegate;
	}

	@Override
	public void showCount(int count) {
		mCounterTextView.setText(String.valueOf(count));
	}
}

MainActivity.java:

public class MainActivity extends MvpAppCompatActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main3);

		((CounterWidget) findViewById(R.id.counter_1)).init(getMvpDelegate());
		((CounterWidget) findViewById(R.id.counter_2)).init(getMvpDelegate());
	}
}