I want my activity to contain 2 fragments, and to switch between them with a button at the action bar. So here is my activity's layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
At the activity's onCreate() I add both fragments to the container... As I need the firstFragment to execute before secondFragment, I'm adding it first, and than hiding secondFragment so user will see fragments in the proper order:
if (findViewById(R.id.fragment_container) != null) {
if (savedInstanceState != null) {
return;
}
FirstFragment firstFragment = new FirstFragment();
SecondFragment secondFragment = new SecondFragment();
firstFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, firstFragment, "FirstFragment")
.add(R.id.fragment_container, secondFragment, "SecondFragment")
.hide(secondFragment)
.commit();
}
When user touches a button at the action bar, the following method gets executed and was supposed to hide one fragment and show the other one, but nothing happens...
public void changeFragment(int id){
Fragment secondFragment = new SecondFragment();
Fragment firstFragment = new FirstFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction()
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
switch (id){
case 1:
//show 2nd
transaction.hide(firstFragment)
.show(secondFragment)
.commit();
break;
case 2:
//show 1st
transaction.hide(secondFragment)
.show(firstFragment)
.commit();
break;
default:
//do nothing
}
}
Any hint on what I'm missing here? Thanks in advance
Actually, your problem looks trivial. Every time you're creating new fragments by:
public void changeFragment(int id){
Fragment secondFragment = new SecondFragment();
Fragment firstFragment = new FirstFragment();
I think the code should be like that, because You just want to hide one and show another, but not add two absolutely new fragments:
public void changeFragment(boolean id){
final Fragment secondFragment = getFragmentManager().findFragmentByTag(FIRST_FRAGMENT_TAG);
final Fragment firstFragment = getFragmentManager().findFragmentByTag(SECOND_FRAGMENT_TAG);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With