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.
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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With