我想在我的Fragment的onViewCreated方法中访问ViewModel类(它扩展了AndroidViewModel)。下面一行代码应该像android文档说的那样工作。但它没有!
ProductListViewModel viewModel = new ViewModelProvider(this).get(ProductListViewModel.class);
显然最近ViewModelProvider构造函数发生了变化。它需要一个ViewModelProvider.Factory实现作为第二个参数。为什么需要ViewModelProvider.Factory实现以及如何实现?
下面是我的Fragment类:
public class HomeFragment extends Fragment {
private HomeListAdapter homeListAdapter;
public HomeFragment() {
// Required empty public constructor
}
public static HomeFragment newInstance() {
return new HomeFragment();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
homeListAdapter = new HomeListAdapter(getContext());
RecyclerView homeRecyclerView = view.findViewById(R.id.rv_products);
homeRecyclerView.setAdapter(homeListAdapter);
homeRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ProductListViewModel viewModel = new ViewModelProvider(this).get(ProductListViewModel.class);
viewModel.getAllProducts().observe(this, new Observer<List<Product>>() {
@Override
public void onChanged(List<Product> products) {
homeListAdapter.setProducts(products);
}
});
}
}
这是我的ViewModel:
public class ProductListViewModel extends AndroidViewModel {
private ProductRepository mRepository;
private LiveData<List<Product>> mAllProducts;
public ProductListViewModel(@NonNull Application application) {
super(application);
mRepository = new ProductRepository(application);
mAllProducts = mRepository.getAllProducts();
}
public LiveData<List<Product>> getAllProducts() {
return mAllProducts;
}
public void insert(Product product) {
mRepository.insert(product);
}
}
1条答案
按热度按时间eyh26e7m1#
因为ViewModelProvider不知道ViewModel如何注入构造函数。
你必须实现接口
ViewModelProvider.AndroidViewModelFactory
在Kotlin中:
AndroidViewModel提供了应用程序上下文,这对于单元测试来说是有问题的。单元测试不应该处理任何Android生命周期,比如上下文。