获取视图和视图模型以使用通用协议进行通信



我试图告诉视图它需要使用 LiveData 导航到两个目的地之一:

class IntroFragment : Fragment()
{
private lateinit var introViewModel : IntroViewModel
override fun onCreateView( inflater : LayoutInflater,
container : ViewGroup?,
savedInstanceState : Bundle?): View? 
{
introViewModel = ViewModelProviders.of( this ).get( IntroViewModel::class.java )
return inflater.inflate( R.layout.fragment_Intro, container, false )
}
override
fun onViewCreated( view: View, savedInstanceState: Bundle? )
{
introViewModel.navigateToSection1.observe(this, Observer {
Navigation.findNavController( view ).navigate( R.id.action_showSection1 )
});
introViewModel.navigateToSection2.observe(this, Observer {
Navigation.findNavController( view ).navigate( R.id.action_showSection2 )
});
}
}

介绍视图模型:

class IntroViewModel : ViewModel()
{
private val _navigateToSection1 = MutableLiveData<Boolean>()
val navigateToNotificationSettings: LiveData<Boolean>
get() = _navigateToSection1
private val _navigateToSection2 = MutableLiveData<Boolean>()
val navigateToSection2: LiveData<Boolean>
get() = _navigateToSection2
init
{
_navigateToSection1 = true
}
}

问题是我需要从视图模型中给出至少 5 个命令才能查看。我想的解决方案之一是定义一个接口:

interface IntroProtocol
{
fun navigateToSection1()
fun navigateToSection2()
}

然后将接口方法作为参数传递回视图,如下所示:

介绍视图模型:

class IntroViewModel : ViewModel()
{
private val _navigateTo = MutableLiveData<IntroProtocol>()
val navigateTo: LiveData<IntroProtocol>
get() = _navigateTo
init
{
_navigateTo = IntroProtocol.navigateToSection1() // I get "Unresolved reference navigateToSection1"
}
}

然后我可以像这样在视图中实现相同的介绍协议:

class IntroFragment : Fragment(), IntroProtocol
{
private lateinit var introViewModel : IntroViewModel
override fun onCreateView( inflater           : LayoutInflater,
container          : ViewGroup?,
savedInstanceState : Bundle?         ): View?
{
introViewModel = ViewModelProviders.of( this ).get( IntroViewModel::class.java )
return inflater.inflate( R.layout.fragment_Intro, container, false )
}

override fun onViewCreated( view: View, savedInstanceState: Bundle? )
{
introViewModel.navigateTo.observe( this, Observer {
callLocalMethodByName( this ) // not sure how call the local method by name dynamically
});
}

override fun navigateToSection1()
{
Navigation.findNavController( view ).navigate( R.id.action_showSection1 )
}

override fun navigateToSection2()
{
Navigation.findNavController( view ).navigate( R.id.action_showSection2 )
}
}

但我不明白该怎么做,如果可能的话。我想传递接口方法的原因是,拥有一个干净的定义/协议会非常方便 ViewModel 知道它可以在视图上调用哪些方法,并且视图将继承它们,这将产生良好的结构。这可能吗?如果没有,还有什么选择?

我会说你不需要接口,但要给你的 MutableLiveData 一个值,你需要这样做:

_navigateToSection1.value = true

相关内容

  • 没有找到相关文章

最新更新