Android - How do I “start” or “initialize” a Fragm

2020-04-04 05:51发布

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.

1条回答
够拽才男人
2楼-- · 2020-04-04 06:04

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.

查看更多
登录 后发表回答