如何使用RecyclerView替换片段

时间:2018-01-19 17:47:58

标签: android android-fragments android-recyclerview

我有RecyclerView我有数据和适配器来处理所有点击。当我从RecyclerView点击某个项目时,我想要加载一个片段。现在我想要的是,当从同一个RecyclerView点击一个项目时,用片段替换Recycler View

我试过这个,但是它遇到了错误

适配器

holder.cvContact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SingleContactFragment singleContactFragment = SingleContactFragment.newInstance(contact);
                FragmentTransaction transaction = ((Activity) context).getFragmentManager().beginTransaction();
                transaction.replace(R.id.rv_contact_list, singleContactFragment);
                transaction.commit();
            }
        });

其中 rv_contact_list 是当前的RecyclerView。

错误是

01-19 20:35:01.892 13088-13088/com.xzii.pkg E/AndroidRuntime: FATAL EXCEPTION: main
                                                          Process: com.xzii.pkg, PID: 13088
                                                          java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.support.v7.widget.RecyclerView$ViewHolder.shouldIgnore()' on a null object reference
                                                              at android.support.v7.widget.RecyclerView.findMinMaxChildLayoutPositions(RecyclerView.java:3869)
                                                              at android.support.v7.widget.RecyclerView.dispatchLayoutStep1(RecyclerView.java:3604)
                                                              at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3408)

1 个答案:

答案 0 :(得分:0)

基本上,该错误抱怨分配给RecyclerView适配器的“上下文数据不足”。尝试将适配器设置为null并删除它,然后添加新片段。现在只有Kotlin示例代码。

val topicListFragment:TopicListFragment = supportFragmentManager.findFragmentById(R.id.topicListFragment) as TopicListFragment
topicListFragment.removeAdaptor()
supportFragmentManager.beginTransaction().remove(topicListFragment).commit()
val topicFragment = TopicFragment()
supportFragmentManager.beginTransaction().add(R.id.homeContent, topicFragment).commit()

清空适配器后,您可能不再需要删除片段,日志消息显示

  

RecyclerView:未连接适配器;跳过布局