Search code examples
androidandroid-fragmentsandroid-fragmentactivityandroid-tabsfragmentmanager

How to pass one fragment to another fragment in a tab menu?


First Screen

After the user fill the blanks this screen showed up:

Second Screen

This is an alert dialog. It's code here:

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
  builder.setTitle("Congratulations!");
  builder.setMessage("You finished Level 1. Do you want to start Level 2?");
  builder.setNegativeButton("Not now", new DialogInterface.OnClickListener(){
      public void onClick(DialogInterface dialog, int id) {

      }
  });
  builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int id)  {

      }
  });

  builder.show();

I want to pass "Level 2" tab when user click "YES" button.

This is what I tried in onClick:

FragmentManager fm = getChildFragmentManager();
fm.beginTransaction().replace(R.layout.activity_level2, new Level2()).commit();

I get this error:

java.lang.IllegalArgumentException: No view found for id 0x7f04001f (translatingthecaps.translatethecaps:layout/activity_level2) for fragment Level2{60d2f9f #0 id=0x7f04001f}

I just have only this code in Level 2 Fragment:

public class Level2 extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.activity_level2, container, false);

        return view;
    }
}

Before alert dialog showed up I can see "Level 2" tab.

Third Screen


Solution

  • When you use a pager, you don't have to explicitly call a FragmentTransaction, all you have to do is

    pager.setCurrentItem(2);
    

    Since your pager isn't accessible from your fragment you should use a listener to set a callback to the activity, here is how to use it How to implement OnFragmentInteractionListener