配置更改后,片段中的实时数据未触发

时间:2019-01-20 12:05:18

标签: android android-fragments android-lifecycle android-livedata android-viewmodel

更改配置后,在我的片段中不再触发观察者。我真的不明白我在代码中缺少什么(它正在使用最新的androidx支持库)。

活动:

@Override
protected void onCreate(Bundle savedInstanceState) {

    FragmentManager fragMgr = getSupportFragmentManager();
    itemListFragment = (ItemListFragment) fragMgr.findFragmentById(R.id.container_fragment_items);

    if (itemListFragment == null) {
    itemListFragment = ItemListFragment.newInstance();
    fragMgr.beginTransaction()
            .add(R.id.container_fragment_items, itemListFragment)
            .commit();
    }
...

片段:

@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_item_list, container, false);

    mainViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
    mainViewModel.getAllItems().observe(getViewLifecycleOwner(), items -> adapter.setItems(items));
...

MainViewModel:

public class MainViewModel extends AndroidViewModel {

    private MainRepository mMainRepository;
    private LiveData<List<Item>> mAllItems;

    public MainViewModel(Application application) {
        super(application);
        mMainRepository = new MainRepository(application);
        mAllItems = mMainRepository.getAll();
    }

    public LiveData<List<Item>> getAllItems() {
        return mAllItems;
    }
...

0 个答案:

没有答案