Start FragmentTransaction from within ArrayAdapter

前端 未结 3 1548
感情败类
感情败类 2020-12-30 13:44

I have a ListView with several rows. Each row has a button.

I want the button to start a FragmentTransaction to replace the Fragment that

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-30 14:14

    getSupportFragmentManager() is only defined for the class FragmentActivity, not for Context. Thus, the compiler can't resolve the call if you try to call it on an object of type Context.

    You can use reflection to do this in a safe way. This will always work as long as you pass your FragmentActivity as the Context. Note: FragmentActivity is a subclass of Context, and thus you can pass FragmentActivity wherever you can pass Context.

    So use this code instead:

    if (getContext() instanceof FragmentActivity) {
        // We can get the fragment manager
        FragmentActivity activity = (FragmentActivity(getContext()));
        FragmentTransaction t = activity.getSupportFragmentManager().beginTransaction();
    }
    

提交回复
热议问题