0

I am building an activity (MainActivity.kt) with a "android.support.design.widget.BottomNavigationView" which has multiple tabs. When a user taps a tab then "BottomNavigationView.OnNavigationItemSelectedListener" should present a corresponding fragment.

Question:

How to set at runtime in onCreateView method a different fragment than the defined in layout file by "android:name" attribute.

MainActivity.kt

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
    }

Layout/ActivityMain.xml


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/main_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">


    <fragment
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:name="com.developer.myapplication.Locator"
            android:id="@+id/fragment"
            />

    <android.support.design.widget.BottomNavigationView
            android:id="@+id/navigation"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:background="?android:attr/windowBackground"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:menu="@menu/navigation"
            app:layout_constraintTop_toBottomOf="@+id/fragment"
            app:layout_constraintStart_toStartOf="parent"/>

</android.support.constraint.ConstraintLayout>
Blazej SLEBODA
  • 8,936
  • 7
  • 53
  • 93

1 Answers1

1

If you want to change a fragment at runtime you should be using a FrameLayout as a container for your fragment instead of using the fragment tag. Once you use a FrameLayout, it is very easy to swap fragments during runtime; you can just use getFragmentManager().beginTransaction().replace(R.id.FrameLayoutId, new MyFragment()).commit(). Furthermore, you normally use the fragment tag for fragments that are there to stay (meaning you are not planning to replace them or modify them during runtime). For more information you can take a look at how master-detail view is implemented with fragments (Android: when / why should I use FrameLayout instead of Fragment?)

Hope this helps! :)

AvidRP
  • 373
  • 2
  • 11