Skip to content

Quick start with ViewState

Vitaly Vivchar edited this page Sep 23, 2020 · 13 revisions

NOTE: start from v3.0.0 ViewBinder was renamed to ViewRenderer, CompositeViewBinder to CompositeViewRenderer ViewState and ViewStateProvider have new interfaces

NOTE: don't use ViewState if you can save a value in your ViewModel, ViewState should be used for some edge cases like these: save scroll positions, save some edit text values while scroll etc.

Step 1: Add getID() method to your model:

public class EditViewModel implements ViewModel {

	public int getID() {
		return mID; /* uniqueID of your model */
	}
}

Step 2: Create ViewState for your ViewModel:

import com.github.vivchar.rendererrecyclerviewadapter.ViewHolder;

public class EditViewState implements ViewState<ViewHolder>, Serializable {

	private final String mEnteredText;

	@Override
	public void clear(@NonNull final ViewHolder holder) {
		holder.getViewFinder().setText(R.id.your_edit_text, "");
	}

	@Override
	public void save(@NonNull final ViewHolder holder) {
		EditText editText = holder.getViewFinder().find(R.id.your_edit_text);
		mEnteredText = editText.getText().toString();
	}

	@Override
	public void restore(@NonNull final ViewHolder holder) {
		holder.getViewFinder().setText(R.id.your_edit_text, mEnteredText);
	}
}

Note: if you use CompositeViewBinder then you should extend CompositeViewState

Step 3: Create ViewStateProvider for your ViewModel:

public class EditViewStateProvider implements ViewStateProvider<EditViewModel, ViewHolder> {
	
	@Override
	public ViewState createViewState() {
		return new EditViewState();
	}

	@Override
	public int createViewStateID(@NonNull final EditViewModel model) {
		return model.getID(); /* using the ID of ViewModel as an ID of ViewState */
	}
}

Step 4: Create ViewRenderer for your ViewModel:

private ViewRenderer getYourViewRenderer() {
	return new ViewRenderer<>(
			R.layout.your_edit_text_item_layout,
			EditViewModel.class,
			(model, finder, payloads) -> {
				/* your binding */
			},
			new EditViewStateProvider()
	);
}

Step 5: Register your ViewRenderer:

adapter.registerRenderer(getEditViewRenderer());