Android: Opening a Fragment from another

后端 未结 1 1567
时光说笑
时光说笑 2021-01-24 02:35

I am new to Android and this is my second app. I am creating a tabbed activity where the first fragment has a form to create a new task, the second fragment has the list of all

1条回答
  •  隐瞒了意图╮
    2021-01-24 02:56

    I saw your branch and noticed that you are using a ViewPager and trying to use FragmentTransaction to update the fragments inside the ViewPager. This does not work as the fragments will already have been created when the ViewPagerAdapter is created and cannot be attached to the ViewPager through a FragmentTransaction.

    Here is how I solved it. Since I was using a ViewPager, using FragmentTransaction as below did not work:

    Wrong way:

    FragmentManager fm = getSupportFragmentManager();
    android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();
    CommentsFragment commentsFragment = CommentsFragment.newInstance(mTaskId, mTaskName);
    ft.replace(R.id.container, commentsFragment);
    ft.addToBackStack(null);
    ft.commit();
    

    With the ViewPager, I had to update the adapter populating it and then set it to the correct fragment. This is what I did:

    Right way:

    In the onListItemClick() in the TasksFragment, call this interface method onFragmentInteraction. And then in the main activity AddTask, implement it as below:

    @Override
    public void onFragmentInteraction(String taskId, String taskName, String assigneeRef) { 
        CommentsFragment commentsFragment = CommentsFragment.newInstance(taskId, taskName);
        mSectionsPagerAdapter.fragmentList.remove(2);
        mSectionsPagerAdapter.fragmentList.add(commentsFragment);
        mSectionsPagerAdapter.notifyDataSetChanged();
        mViewPager.setCurrentItem(2);
    }
    

    Hope this helps you and someone else who faces a problem with updating Fragments inside a ViewPager.

    0 讨论(0)
提交回复
热议问题