I'm doing a simple example with fragments and what I need is that when I click the first button the replace button will pop up for Fragmen1 and when I click the second button Fragment2.
When I start the application the fragment I left in the XML appears normally, but the problem happens when I click on any of the buttons to replace a fragment , this happens:
Whathappensisthatthefragmentthatwasinthebeginningdoesnotdisappear,itsimplystaysatthetopofthespacereservedforfragments.
FollowtheXMLsandClasses:
publicclassMainActivityextendsActivity{Buttonbtn1,btn2;FragmentManagerfm;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btn1=(Button)findViewById(R.id.btnFrag1);btn2=(Button)findViewById(R.id.btnFrag2);fm=getFragmentManager();btn1.setOnClickListener(newView.OnClickListener(){@OverridepublicvoidonClick(Viewv){Fragmento1f1=newFragmento1();FragmentTransactiontransaction=fm.beginTransaction();transaction.addToBackStack(null);transaction.replace(R.id.fragmentPlace,f1);transaction.commit();}});btn2.setOnClickListener(newView.OnClickListener(){@OverridepublicvoidonClick(Viewv){Fragmento2f2=newFragmento2();FragmentTransactiontransaction=fm.beginTransaction();transaction.replace(R.id.fragmentPlace,f2);transaction.addToBackStack(null);transaction.commit();}});}publicclassFragmento1extendsFragment{@OverridepublicViewonCreateView(LayoutInflaterinflater,ViewGroupcontainer,BundlesavedInstanceState){returninflater.inflate(R.layout.fragment_1,container,false);}}publicclassFragmento2extendsFragment{@OverridepublicViewonCreateView(LayoutInflaterinflater,ViewGroupcontainer,BundlesavedInstanceState){returninflater.inflate(R.layout.fragment_2,container,false);}}
<LinearLayoutandroid:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical"
android:gravity="center">
<Button
android:id="@+id/btnFrag1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fragment 1"/>
<Button
android:id="@+id/btnFrag2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fragment 2"/>
</LinearLayout>
<LinearLayout
android:id="@+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<fragment
android:id="@+id/fragmentPlace"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.example.dideconto.exemplofragmentsimples.Fragmento2"></fragment>
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fragmento 2"/>
I'd like to know where I'm going wrong.