在配置更改时重新创建Viewmodel get

时间:2019-10-27 08:21:19

标签: android android-fragments android-viewmodel android-mvvm

每次执行方向更改时,我都会创建Viewmodel。我一直认为ViewModelProviders会给我返回相同的on config更改实例。我在onActivityCreated中初始化我的视图模型。我正在使用具有单个活动架构的导航组件。我在活动中使用导航主机片段的位置。这是我的家碎片。

public class EmployeeDirectoryFragment extends Fragment implements 
EmployeeDirectoryAdapter.ProfilePictureClickListener {
private EmployeeDirectoryViewModel employeeDirectoryViewModel;
private EmployeeDirectoryFragmentBinding employeeDirectoryFragmentBinding;
private EmployeeDirectoryAdapter employeeDirectoryAdapter;
private List<Employee> employees = new ArrayList<>();

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                         @Nullable Bundle savedInstanceState) {
    employeeDirectoryFragmentBinding = DataBindingUtil.inflate(inflater, R.layout.employee_directory_fragment, container, false);
    return employeeDirectoryFragmentBinding.getRoot();
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    employeeDirectoryViewModel = ViewModelProviders.of(this).get(EmployeeDirectoryViewModel.class);
    employeeDirectoryFragmentBinding.directoryView.setLayoutManager(new LinearLayoutManager(getContext()));
    employeeDirectoryAdapter = new EmployeeDirectoryAdapter(employees, this);
    employeeDirectoryFragmentBinding.directoryView.setAdapter(employeeDirectoryAdapter);

    employeeDirectoryFragmentBinding.setEmployeeViewModel(employeeDirectoryViewModel);
    employeeDirectoryFragmentBinding.setLifecycleOwner(this);
    employeeDirectoryViewModel.getEmployees().observe(this, new Observer<List<Employee>>() {
        @Override
        public void onChanged(List<Employee> updatedEmployees) {
            employees.addAll(updatedEmployees);
            employeeDirectoryAdapter.notifyDataSetChanged();
        }
    });

    employeeDirectoryViewModel.hasError().observe(this, new Observer<Boolean>() {
        @Override
        public void onChanged(Boolean hasError) {
            employeeDirectoryFragmentBinding.directoryView.setVisibility(hasError ? View.GONE : View.VISIBLE);
            employeeDirectoryFragmentBinding.emptyView.setVisibility(hasError ? View.VISIBLE : View.GONE);
        }
    });
}

@Override
public void onProfilePictureClick(String url) {
    Navigation.findNavController(getView()).navigate(EmployeeDirectoryFragmentDirections.actionEmployeeDirectoryFragmentToProfileFragment2(url));
}
}

0 个答案:

没有答案