Skip to content

Instantly share code, notes, and snippets.

@hbmartin
Created July 21, 2017 00:18
Show Gist options
  • Save hbmartin/4c69e8520f560c2b9e7d23fff4ce1930 to your computer and use it in GitHub Desktop.
Save hbmartin/4c69e8520f560c2b9e7d23fff4ce1930 to your computer and use it in GitHub Desktop.
// subclass must implement injection
public abstract class BoundVmFragment<VM extends ViewModel, VDB extends ViewDataBinding> extends LifecycleFragment {
@Inject protected ViewModelProvider.Factory viewModelFactory;
@Inject protected NavigationController navigationController;
protected FragmentDataBindingComponent dataBindingComponent = new FragmentDataBindingComponent(this);
protected VM viewModel;
protected AutoClearedValue<VDB> binding;
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
viewModel = ViewModelProviders.of(this, viewModelFactory).get(getVmClass());
setupFragment(getArguments());
setupUi();
setupObservers();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
VDB dataBinding = DataBindingUtil
.inflate(inflater, getLayout(), container, false,
dataBindingComponent);
binding = new AutoClearedValue<>(this, dataBinding);
return dataBinding.getRoot();
}
// ____ _ _ ____ ____ ____ _ ___ ____
// | | | | |___ |__/ |__/ | | \ |___
// |__| \/ |___ | \ | \ | |__/ |___
protected abstract int getLayout();
protected abstract Class<VM> getVmClass();
protected void setupFragment(Bundle args) { }
protected abstract void setupUi();
protected abstract void setupObservers();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment