Home » Android » java – Android – How do I "start" or "initialize" a Fragment from an activity?

java – Android – How do I "start" or "initialize" a Fragment from an activity?

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have a class called DummyFragment that extends Fragment.

public class DummyFragment extends Fragment {

    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setRetainInstance(true);

        Log.i("myapp","test");
    }
}

Now, in my parent activity, I want to “run” this fragment.

This is my FirstActivity.java:

public class FirstActivity {

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);

        // How do I run/start my fragment? I want it's onCreate method to fire
        Fragment fraggy = new DummyFragment();
    }
}

How do I run/start my fragment? I want my DummyFragment‘s onCreate method to fire.

How to&Answers:

There’s plenty of documentation! Everything you need is already here.

FragmentManager fragmentManager = getFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

Fragment fraggy = new DummyFragment();
fragmentTransaction.add(R.id.fragment_container, fraggy);
fragmentTransaction.commit();

Of course, you’ll need the container in you activity layout.