从 RecyclerView 适配器创建新片段 class

Create New Fragment from RecyclerViewAdapter class

我正在尝试在用户单击我的回收站视图中的项目时创建一个新的片段实例。它在线上崩溃:"fragmentTransactiion.commit()" 抛出 JavaIllegalStateException 表示 Activity 已被销毁。这是我的 RecyclerViewAdapter class 中启动新片段的代码:

    @Override
    public void onClick(View v) {
        String poster_id = event_picture.getProfileId();
        DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference()
                .child("events").child("userid").child(poster_id);
        if (databaseReference != null) databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                Event event = dataSnapshot.getValue(Event.class);
                String clickedEventName = event_name.getText().toString();
                String clickedEventLocation = event_location.getText().toString();
                String eventName = event.getTitle();
                String eventAddress = event.getAddress();

                if (clickedEventLocation.equals(eventAddress) && clickedEventName.equals(eventName)){
                    displayEvent(event);
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }
}

public static void displayEvent(Event e){
    Bundle bundle = getBundle(e);
    DisplayEvent displayEvent = new DisplayEvent();
    displayEvent.setArguments(bundle);
    AppCompatActivity context = new AppCompatActivity();
    FragmentManager fragmentManager = context.getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.setCustomAnimations(android.R.anim.slide_in_left,
            android.R.anim.slide_out_right);
    fragmentTransaction.replace(R.id.fragment_display, displayEvent, "display_event");
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();
}

我不太确定我做错了什么。任何帮助将不胜感激!!

您正在尝试访问以下行中 non-existent/created Activity 的上下文。

AppCompatActivity context = new AppCompatActivity();
FragmentManager fragmentManager = context.getSupportFragmentManager();

你应该把它改成

FragmentManager fragmentManager = activity.getSupportFragmentManager();

您可以通过持有对 RecyclerView 所属的 activity 的引用来实现此目的,它是在其中创建的。上面代码块中的 activity 应该是创建它的那个,而不是新的 Activity 实例。

更好的方法是将您自己的自定义接口作为回调通知其侦听器 (activity)。然后,activity 应该执行 Fragment 或 Activity 转换.