forked from inloop/AndroidViewModel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ViewModelBaseFragment.java
105 lines (86 loc) · 2.8 KB
/
ViewModelBaseFragment.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package eu.inloop.viewmodel.base;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.annotation.CallSuper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import eu.inloop.viewmodel.AbstractViewModel;
import eu.inloop.viewmodel.BR;
import eu.inloop.viewmodel.IView;
import eu.inloop.viewmodel.ViewModelHelper;
public abstract class ViewModelBaseFragment<T extends IView, R extends AbstractViewModel<T>, B extends ViewDataBinding> extends Fragment implements IView {
private ViewModelHelper<T, R> mViewModelHelper;
private B mBinding;
@CallSuper
@Override
public void onCreate(@Nullable final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewModelHelper = new ViewModelHelper<>(getViewModel());
getViewModelHelper().onCreate(savedInstanceState, getArguments());
}
public abstract B inflateBindingLayout(LayoutInflater layoutInflater, ViewGroup container);
@CallSuper
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mBinding = inflateBindingLayout(inflater, container);
mBinding.setVariable(BR.view, this);
mBinding.setVariable(BR.viewModel, getViewModel());
return mBinding.getRoot();
}
@CallSuper
@Override
public void onSaveInstanceState(@NonNull final Bundle outState) {
super.onSaveInstanceState(outState);
getViewModelHelper().onSaveInstanceState(outState);
}
@CallSuper
@Override
public void onStart() {
super.onStart();
getViewModelHelper().onStart();
}
@CallSuper
@Override
public void onStop() {
super.onStop();
getViewModelHelper().onStop();
}
@CallSuper
@Override
public void onDestroyView() {
getViewModelHelper().onDestroyView(this);
super.onDestroyView();
}
@CallSuper
@Override
public void onDestroy() {
getViewModelHelper().onDestroy(this);
super.onDestroy();
}
@NonNull
public abstract R getViewModel();
public B getBinding() {
return mBinding;
}
@NonNull
public ViewModelHelper<T, R> getViewModelHelper() {
return mViewModelHelper;
}
@Override
public void removeViewModel() {
mViewModelHelper.removeViewModel();
}
/**
* Call this after your view is ready - usually on the end of {@link
* Fragment#onViewCreated(View, Bundle)}
*
* @param view view
*/
protected void setModelView(@NonNull final T view) {
getViewModelHelper().setView(view);
}
}