Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 756
wiseindy Avatar asked Nov 11 '13 20:11

wiseindy


People also ask

How do you associate a fragment with an activity?

Add a fragment to an activity You can add your fragment to the activity's view hierarchy either by defining the fragment in your activity's layout file or by defining a fragment container in your activity's layout file and then programmatically adding the fragment from within your activity.

Can I call fragment method from activity?

Originally Answered: How can I call fragment methods from activity to fragment in Android ? If you actually meant to call a fragment from its parent activity then you can use this: ExampleFragment fragment = (ExampleFragment) getFragmentManager(). findFragmentById(R.

What is the process of starting a new fragment in Android?

To create a blank Fragment , expand app > java in Project: Android view, select the folder containing the Java code for your app, and choose File > New > Fragment > Fragment (Blank).


1 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.

like image 156
Blacklight Avatar answered Oct 04 '22 19:10

Blacklight