我使用的是在Google I/O2018上展示的Android导航,我似乎可以通过绑定到某个视图或使用NavHost
从片段中获取它来使用它.但是,我需要根据几个条件从我的第一个片段导航到ViewModel中的另一个特定视图.对于ViewModel
,我延长了AndroidViewModel
,但是我不知道下一步该怎么做.我不能将getApplication
强制转换为片段/活动,也不能使用NavHostFragment
.另外,我不能只将导航绑定到onClickListener
,因为startFragment
只包含一个ImageView
.我如何从ViewModel
开始导航?
class CaptionViewModel(app: Application) : AndroidViewModel(app) {
private val dealerProfile = DealerProfile(getApplication())
val TAG = "REGDEB"
fun start(){
if(dealerProfile.getOperatorId().isEmpty()){
if(dealerProfile.isFirstTimeLaunch()){
Log.d(TAG, "First Time Launch")
showTour()
}else{
showCodeFragment()
Log.d(TAG, "Show Code Fragment")
}
}
}
private fun showCodeFragment(){
//??
}
private fun showTour(){
//??
}
}
我的碎片
class CaptionFragment : Fragment() {
private lateinit var viewModel: CaptionViewModel
private val navController by lazy { NavHostFragment.findNavController(this) }
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
viewModel = ViewModelProviders.of(this).get(CaptionViewModel::class.java)
return inflater.inflate(R.layout.fragment_caption, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel.start()
}
}
I want to keep logic of navigation in ViewModel