【问题标题】:Quick fragment switching view binding null快速片段切换视图绑定 null
【发布时间】:2020-12-21 09:07:15
【问题描述】:

我在选项卡布局中有 2 个片段,在它们之间快速切换会导致视图返回为 null,使用 ViewBinding。这是因为构建 FragmentXBinding 类的延迟吗?

用法示例:

chatadapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onItemRangeInserted(int positionStart, int itemCount) {
                binding.chatRecyclerView.smoothScrollToPosition(0);
            }
        });

错误:

java.lang.NullPointerException: Attempt to read from field 'androidx.recyclerview.widget.RecyclerView com.iku.databinding.FragmentChatBinding.chatRecyclerView' on a null object reference

【问题讨论】:

  • 你的binding是空的。确保你在onCreateView中初始化视图绑定
  • 它在 onCreateView 里面,我在快速切换片段时得到它。
  • ohhh .. 在这种情况下,请在 onViewCreated(...) 中初始化您的绑定
  • @chandmohd 它不起作用
  • @ThomasBernhard 我不完全!但是将与视图绑定相关的代码放在onViewCreated(..) 中会更好,并且必须在应用程序中删除一些实时侦听器以避免这种 NPE。甚至在onStop()中分离监听器

标签: android android-fragments data-binding android-viewbinding


【解决方案1】:

FragmentX

 FragmentXBinding binding;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    binding = FragmentChatBinding.inflate(inflater, container, false);
    init();
    return binding.getRoot();
}

 private void init() {
    // all initialization 
}

这有助于我使用空引用解决我的错误

【讨论】:

    猜你喜欢
    • 2011-02-01
    • 1970-01-01
    • 2011-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-08
    相关资源
    最近更新 更多