如何解决ViewModel通过BottomNavigationView切换初始化了两次
我有一个带有BottomNavigationView的MVVMCross Android应用程序,其中在MainActivity OnCreate方法中,我创建片段列表,导航以查看匹配它们的模型并打开第一个片段
异步OnCreate():
BuildFragmentsList();
if (_firstTimeCreated)
{
_firstTimeCreated = false;
await viewmodel.ShowInitialviewmodelsCommand.ExecuteAsync();
}
LoadFragment(Resource.Id.menu_first);
BuildFragmentsList():
private void BuildFragmentsList()
{
MvxFragment firstFragment = FirstFragment.NewInstance();
MvxFragment secondFragment = SecondFragment.NewInstance();
fragments.Add(firstFragment);
fragments.Add(secondFragment);
}
ShowInitialviewmodelsCommand():
private async Task ShowInitialviewmodelsCommandExecute()
{
await NavigationService.Navigate<Firstviewmodel>();
await NavigationService.Navigate<Secondviewmodel>();
IsInitialized = true;
}
LoadFragment():
private void LoadFragment(int id)
{
try
{
switch (id)
{
case Resource.Id.menu_first:
SwitchFragment(0);
break;
case Resource.Id.menu_second:
SwitchFragment(1);
break;
}
}
catch (Exception exception)
{
System.Diagnostics.Debug.WriteLine($"Exception: {exception.Message}");
Crashes.Trackerror(exception);
}
}
SwitchFragment():
private void SwitchFragment(int pos)
{
if (fragments.Count > 0)
SupportFragmentManager.BeginTransaction()
.Replace(Resource.Id.content_frame,fragments[pos])
.Commit();
}
我不明白为什么两个viewmodel都要初始化两次,首先是调用ShowInitialviewmodelsCommand
时,还是在BottomNaviagtionView
上选择它时。
在这种情况下,当我导航到“第二视图模型”时,它将再次初始化一次并再次加载内容
所有下一个开关都通过,而没有调用Initialize
方法
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。