我正在尝试使用新的android体系结构组件,但我一时糊涂了。
我创建了一个viewmodel类
public class BuyViewModel extends ViewModel {
private BuyRepository buyRepository;
private LiveData<Adverts> advertsLiveData;
private boolean isLoading;
private int currentPage;
@Inject
public BuyViewModel(BuyRepository buyRepository) {
this.buyRepository = buyRepository;
}
public void init(int currentPage) {
this.currentPage = currentPage;
if (this.advertsLiveData != null) {
return;
}
Timber.tag("logi").d("BuyViewModel > init -> ");
advertsLiveData = buyRepository.getAdverts(currentPage);
}
public LiveData<Adverts> getAdvertsLiveData() {
return advertsLiveData;
}
}
在我的生命周期标签中观察livedata
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
buyViewModel = ViewModelProviders.of(this, viewModelFactory).get(BuyViewModel.class);
buyViewModel.init(1);
buyViewModel.getAdvertsLiveData().observe(this, adverts -> {
Timber.tag("logi").d("BuyFragment > onActivityCreated -> ");
assert adverts != null;
adapter.addMoreAdverts(adverts.getResults());
});
setupViews();
}
但是当我用另一个片段替换这个片段并切换回这个片段时,方法
onChange
被调用了两次,并在rvAdapter
中添加了相同数据的两部分。 最佳答案
我解决了!!!!
在创建viewmodel类时,我将“this”第一个参数传递给方法buyViewModel = ViewModelProviders.of(**this**, viewModelFactory).get(BuyViewModel.class);
但我需要传递“getActivity()”,代码看起来是这样的buyViewModel = ViewModelProviders.of(**getActivity()**,viewModelFactory).get(BuyViewModel.class);
关于android - 为什么 fragment 重新创建时onChange()调用了两次,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44863065/