How to open a Fragment on button click from a fragment in Android

后端 未结 4 1773
醉梦人生
醉梦人生 2020-11-28 09:12

I have some button on my HomeFragment i want to to open a Fragment on button click from a fragment . Something like Navigation. I am trying with bellow code but did not work

4条回答
  •  误落风尘
    2020-11-28 09:14

    I have a simple trick to it! This is the code in MainActivity:

    Intent intent=new Intent(getApplicationContext(),Main2Activity.class);
            intent.putExtra("pos",1);
            startActivity(intent);
    
    Intent intent1=new Intent(getApplicationContext(),Main2Activity.class);
            intent1.putExtra("pos",2);
            startActivity(intent1);
    

    In Main2Activity which is a NavigationDrawer with fragments

    Bundle extras;
      extras=getIntent().getExtras();
            if(extras!=null)
            {
                position=extras.getInt("pos");
                if(position==1)
                {
                    fragment=new FragmentOne();
    
                    if(fragment !=null)
                    {
                        android.support.v4.app.FragmentManager fragmentManager=getSupportFragmentManager();
                        FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
                        fragmentTransaction.replace(R.id.screen_area,fragment);
                        fragmentTransaction.commit();
                    }
                }
                if(position==2)
                {
                    fragment=new FragmentTwo();
    
                    if(fragment !=null)
                    {
                        android.support.v4.app.FragmentManager fragmentManager=getSupportFragmentManager();
                        FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
                        fragmentTransaction.replace(R.id.screen_area,fragment);
                        fragmentTransaction.commit();
                    }
                }
            }
    

提交回复
热议问题