Ishita Sinha Ishita Sinha - 5 months ago 20
Android Question

Android: Opening a Fragment from another

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 the saved tasks, and the third fragment will show the comments on a task when selected from the list in the second fragment. The third fragment is also supposed to act like a chat activity which posts comments when you type them in and tap the send button. When I implement this chat activity from a separate

Activity
(
CommentsActivity.java
in the GitHub branch in the link below), the app runs absolutely as it is supposed to. However, when I try to implement the same code from the third
Fragment
, I have the following problems:


  • I have to tap the list item (in
    TasksFragment.java
    ) twice before the
    CommentsFragment
    is launched.

  • The fragment remains blank and shows no details or comments.

  • The title bar is messed up. It does set the title correctly when
    CommentsFragment
    is launched for the first time. However, it becomes blank subsequently, when I swipe between the fragments . Sometimes it even shows the title of the last open fragment instead of the one currently open.



You can find all my code here: https://github.com/geekskool/android-teamwork/tree/only_fragments

Other details: I am passing the data between the
TasksFragment
and the
CommentsFragment
with fragment interaction methods that interact with the main activity--
AddTask.java
. This is the only way I know of. If there is a better way, please let me know.

Answer

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, I call this interface method onFragmentInteraction. And then in the main activity AddTask, I 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 someone else who faces a problem with updating Fragments inside a ViewPager.

Comments