Android ViewModel在已加载的数据上导航缓慢



我正在通过ViewModel从Firebase实时数据库加载数据。在我的布局中,我有进度条和回收视图。当我需要首先加载数据时,一切都很顺利,当我点击按钮时,片段立即打开,进度条正在运行,当数据加载时,它停止运行,并显示recycleview。但是,当我再次进入该片段时(数据已经加载(,没有显示进度条(这是可以的(,但大约需要几秒钟才能完成切换,这比我描述的第一种行为慢得多。

所以,我想知道是什么让它在第二种情况下等待这么长时间,我如何覆盖它,这样我的碎片就会先出现,然后再出现在recycleview?

我已经尝试过使用viewstub和dummy视图,但似乎什么都不起作用。。

我的类别碎片

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    homeViewModel = new ViewModelProvider(requireActivity()).get(MenuViewModel.class);
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    
    if(root == null || fragmentState == STATE_STARTUP)
    {
        binding = FragmentCategoryRecyclerBinding.inflate(inflater, container, false);
        root = binding.getRoot();
        binding.categoryRecycler.setHasFixedSize(true);
        binding.categoryRecycler.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false));
        layoutAnimationController = AnimationUtils.loadLayoutAnimation(getContext(), R.anim.layout_item_fade_scale);
        myFoodListAdapter = new MyFoodListAdapter(getContext(), foodModelList, String.valueOf(menuIndex), String.valueOf(categoryIndex));
        binding.categoryRecycler.setAdapter(myFoodListAdapter);
    }
    else
        binding = FragmentCategoryRecyclerBinding.bind(root);
    return root;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    homeViewModel.getMessageError().observe(getViewLifecycleOwner(), s -> Toast.makeText(getContext(), "" + s, Toast.LENGTH_SHORT).show());
    homeViewModel.getMenuList(restaurantId).observe(getViewLifecycleOwner(), menuModels -> {
        if(fragmentState == STATE_STARTUP || fragmentState == STATE_SEARCHING)
        {
            binding.categoryRecycler.setLayoutAnimation(layoutAnimationController);
            myFoodListAdapter.setFoodModelList(menuModels.get(menuIndex).getCategories().get(categoryIndex).getItems());
            binding.progressBar.hide();
            binding.categoryRecycler.setVisibility(View.VISIBLE);
            fragmentState = STATE_INITIALIZED;
            if(foodModelList.isEmpty())
                foodModelList = menuModels.get(menuIndex).getCategories().get(categoryIndex).getItems();
            myFoodListAdapter.notifyDataSetChanged();
        }
    });
}
@Override
public void onDestroyView() {
    binding = null;
    super.onDestroyView();
}

很抱歉回复延迟在onstart中使用viewmodel或androidviewmodel,而不是在创建时使用

最新更新