如何防止在背面片段导航中再次设置视图模型

时间:2019-02-04 15:35:17

标签: android mvvm kotlin navigation android-jetpack

我正在使用Android Jetpack导航,MVVM和dataBinding,并且遇到了一个问题。每次我从详细信息片段导航回来时,我的主List片段都会刷新(再次调用API,并再次绘制recyclerList)。我该如何预防?

这是主列表片段代码:

CREATE TABLE `t1` (`col1` INT, `col2` INT, UNIQUE(`col1`), UNIQUE(`col2`));

}

我还必须补充一点,我正在MainFragment上使用此片段,其中包含viewPager。

我的MainFragment代码:

class PostListFragment : BaseFragment() {

private lateinit var viewModel: PostListViewModel

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {

    val binding = TestFragmentBinding.inflate(inflater, container, false)
    val factory = InjectorUtils.providePostListViewModelFactory()
    viewModel = ViewModelProviders.of(this, factory).get(PostListViewModel::class.java)

    val adapter = MainListAdapter()
    binding.mainList.adapter = adapter

    binding.let {
        it.viewmodel = viewModel
        it.setLifecycleOwner(this@PostListFragment)
    }

    subscribeUi(adapter)
    return binding.root
}

private fun subscribeUi(adapter: MainListAdapter) {

    viewModel.progressVisible.postValue(true)
    addToDisposable(viewModel.getContentRepository().getAllPosts(requireContext())
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe({ result ->
            viewModel.progressVisible.postValue(false)
            adapter.submitList(result)
        }, { error ->
            viewModel.progressVisible.postValue(false)
        }))
}

}

1 个答案:

答案 0 :(得分:0)

需要先检查savedInstanceState中的Activity.onCreate()

if(savedInstanceState == null) {
    ...
}

,并且当它不是null时,请勿给Fragment充气-随后将不会两次调用Fragment.onCreateView()(否则很难从那里返回View)。