Attach a Fragment to the Activity

前端 未结 3 1488
野的像风
野的像风 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

    0 讨论(0)
  • 2021-01-07 16:22

    Replace your code:

    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    MainFragment fragment = new MainFragment();
    fragmentTransaction.add(R.id.activity_main,fragment);
    fragmentTransaction.commit();
    

    By this:

    Fragment fragment = new MainFragment();
    getSupportFragmentManager.begintransaction.replace(R.id.container,fragment).commit;
    
    0 讨论(0)
  • 2021-01-07 16:23

    first of all your take framelayout in activity_main.after that

    fragmentTransaction.add(R.id.framelayout_id,fragment);

    than its working fine

    0 讨论(0)
提交回复
热议问题