I want my activity to contain 2 fragments and switch between them using the button on the action bar. So here is my activity 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>
In the onCreate () action, I add both fragments to the container ... Since I need the first Fragment to execute before secondFragment, I add it first and then hide secondFragment, so the user will see the fragments in the correct 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 the user touches a button on the action bar, the following method is executed and had to hide one fragment and show another, 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:
transaction.hide(firstFragment)
.show(secondFragment)
.commit();
break;
case 2:
transaction.hide(secondFragment)
.show(firstFragment)
.commit();
break;
default:
}
}
Any hint that I'm missing here? thanks in advance