ExecutePendingBindings防止片段过渡动画

时间:2019-04-26 23:14:35

标签: android android-fragments data-binding android-databinding fragment-transitions

我正在尝试向Fragment交易中添加动画。除了一个案例,一切看起来都不错。该Fragment包含一个RecyclerView所设置的databinding。数据也通过ObservableArrayListbinding绑定。

这就是Fragment中发生的事情。

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        mViewModel = ViewModelProviders.of(requireActivity(), mViewModelFactory).get(MainMenuViewModel::class.java)
        setHasOptionsMenu(true)
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_main_menu, container, false)
        return with(mBinding) {
            callback = this@MainMenuFragment
            viewModel = mViewModel
            executePendingBindings()
            root
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        loadMenu()
        subscribeToUserNotification()
        subscribeToPromoItemSearchResult()
    }

启动Activity并按预期工作时,正在加载此片段。但是,在进行任何其他片段事务之后,添加executePendingBindings()之后,不仅会为此片段触发popAnimation。仅存在350个延迟(为过渡设置),并且片段仅出现而没有可见的过渡。

我想删除executePendingBindings(),但是又遇到了另一个问题。方法loadMenu()为回收者更新数据列表,并且在第一次启动时,从Internet查询数据,因此,绑定有时间来初始化所有依赖项,因此延迟很小。但是,当我在第二次Fragment事务之后按回去时,数据已经存在,并且当我的BindingAdapter触发时,回收者的adpter为空,并且根本不显示它。即使方法loadMenu()onViewCreated中,并且绑定是在onCreateView中初始化的。

因此解决方案要么是解决过渡问题,要么是解决未按时初始化绑定的问题。

添加绑定适配器和xml以供参考

@BindingAdapter("category_list")
    public static void addCategoriesToAdapter(RecyclerView recyclerView, ObservableArrayList<MainMenuCategory> catList) {
        MenuCategoriesAdapter adapter = (MenuCategoriesAdapter) recyclerView.getAdapter();
        if (adapter != null) { //here the adapter happens to be null when onBackPressed after a second fragment transaction
            adapter.getCategories().clear();
            adapter.getCategories().addAll(catList);
            adapter.notifyDataSetChanged();
        }
    }

        <androidx.recyclerview.widget.RecyclerView
            app:adapter="@{callback.getCategoriesAdapter()}"
            app:category_list="@{viewModel.catList}"
            app:manager="@{callback.getMenuLayoutManager()}" />

0 个答案:

没有答案