I'm in trouble with fragment tag as you can see below:
- My app contain 2 buttons: Fragment 1, Fragment 2
- Also 2 fragment: FirstFragment.java and SecondFragment.java
- Then I set 1 fragment tag which I use as a container for 1 of 2 fragments
Question:
- I used getSupportFragmentManager() to set FirstFragment.java into my fragment tag but it doesn't work. Why?
- If I change fragment tag into FrameLayout, FragmentContainerView it will work. Why?
- How to using fragment tag as a container and calling it in onCreate() programmatically?
My code:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirstFragment firstFragment = new FirstFragment();
SecondFragment secondFragment = new SecondFragment();
getSupportFragmentManager().beginTransaction().add(R.id.flFragment, firstFragment).commit();
findViewById(R.id.btnFrag1).setOnClickListener(view -> {
getSupportFragmentManager().beginTransaction().replace(R.id.flFragment, firstFragment).commit();
});
findViewById(R.id.btnFrag2).setOnClickListener(view -> {
getSupportFragmentManager().beginTransaction().replace(R.id.flFragment, secondFragment).commit();
});
}
}
<Button
android:id="@+id/btnFrag1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fragment 1"
app:layout_constraintEnd_toStartOf="@+id/btnFrag2"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btnFrag2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fragment 2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="@+id/btnFrag1"
app:layout_constraintTop_toTopOf="parent" />
<fragment
android:id="@+id/flFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btnFrag1" />