Attach a Fragment to the Activity

前端 未结 3 1491
野的像风
野的像风 2021-01-07 15:23

I am trying to attach a Fragment to my MainActivity programmatically by using the following code:

@Override
protected void onCreate(Bundle savedInstanceSta         


        
3条回答
  •  南笙
    南笙 (楼主)
    2021-01-07 16:05

    Make a function like that

    public void openFragment(Fragment fragment) {
            FragmentManager manager = getSupportFragmentManager();
            manager.beginTransaction().replace(R.id.fragmentContainer, fragment).commit();
        }
    

    and call this in your onCreate Method

     openFragment(new yourFragment());
    

    In your beginTransaction().replace method you have to pass the view from which you want to replace your fragment with

提交回复
热议问题